Javascript - Dynamically assign onclick event in the loop - javascript

I have very simple html page with js code:
<html>
<head>
<title></title>
</head>
<body>
<div id="divButtons">
</div>
<script type="text/javascript">
var arrOptions = new Array();
for (var i = 0; i < 10; i++) {
arrOptions[i] = "option" + i;
}
for (var i = 0; i < arrOptions.length; i++) {
var btnShow = document.createElement("input");
btnShow.setAttribute("type", "button");
btnShow.value = "Show Me Option";
var optionPar = arrOptions[i];
btnShow.onclick = function() {
showParam(optionPar);
}
document.getElementById('divButtons').appendChild(btnShow);
}
function showParam(value) {
alert(value);
}
</script>
</body>
</html>
That page binds 10 buttons, but when you click on any button it always shows alert "option9". How is it possible assign onclick event to show correspondent option !?
Thanks!

You'll have to do something like this:
btnShow.onclick = (function(opt) {
return function() {
showParam(opt);
};
})(arrOptions[i]);

Consider the fact that when the onclick() function is executed, all it has is:
showParam(optionPar);
, verbatim. The optionPar will be resolve at the time the click event is executed, and at this point it most likely be the latest value you assigned to it. You should generally avoid passing variables in such a way.
The problem you are trying to solve is best solved by re-writing the piece such as:
btnShow.value = "Show Me Option";
var optionPar = arrOptions[i];
btnShow.optionPar = optionPar;
btnShow.onclick = function(e) {
// if I'm not mistaking on how to reference the source of the event.
// and if it would work in all the browsers. But that's the idea.
showParam(e.source.optionPar);
}

The accepted answer seems to work, but seems to be confusing and a somewhat cumbersome way to do it. A better way perhaps might be to use the data attribute for the element you're looking to assign the event listener for. It's simple, easy to understand, and way less code. Here's an example:
btnShow.data = arrOptions[i];
btnShow.onclick = function() {
showParam(this.data);
}

I attach an event handler:
window.onload = function() {
var folderElement;
tagFolders = document.getElementById("folders");
for (i = 0; i < folders.length; i++) {
folderElement = folderButtons[i];
folderElement = document.createElement("button");
folderElement.setAttribute("id", folders[i]);
folderElement.setAttribute("type", "button");
folderElement.innerHTML = folders[i];
if (typeof window.addEventListener !== "undefined") {
folderElement.addEventListener("click", getFolderElement, false);
} else {
folderElement.attachEvent("onclick", getFolderElement);
}
tagFolders.appendChild(folderElement);
}
which can retrieve anything from the element that triggered the event:
// This function is the event handler for the folder buttons.
function getFolderElement(event) {
var eventElement = event.currentTarget;
updateFolderContent(eventElement.id);
}
in which case you have to embed the option inside the element / tag. In my case I use the id.

For jquery, check out the adding event data section from the API:
...
for (var i = 0; i < arrOptions.length; i++) {
$('<input id="btn" type="button" value="Show Me Option"><input>').appendTo("#divButtons")
$('#btn').bind("click", {
iCount: i},
function(event) {
showParam(arrOptions[iCount]);
});
}

The accepted answer is correct but I feel that no real explanation was done.
Let me try to explain, the issue here is classical missing closure.
The variable 'i' is getting increased by 1 per loop iteration,
and the on-click event actually is not being executed, whether only applied to the a element, it getting summarize up to the length of arrOptions which is 10.
So, the loop continues up until 'i' is 10,
Then, whenever the on-click event is being triggered, it takes the value of i which is 10.
now, for the solution,
in the solution we are using a closure, so that when we apply the value of 'i' to the on-click event of the a element, it actually gets the exact value of i at in time.
The inner function of the onclick event create a closure where it references the parameter (arrOptions[i]), meaning what the actual i variable is at the right time.
The function eventually closes with that value safely,
and can then return its corresponding value when the on-click event is being executed.

You pass just the reference of the variable to the function, not it's value. So every time the loop is iterated, it assigns a reference to your anonymous function and all of them point to the same value in memory. But since you use the same variable name in the loop, you overwrite the value of the variable. You can concatenate the variable to a string to preserve it's value. For example like that:
btnShow.onclick = new Function("", "showParam(" + arrOptions[i] + ");");
The first parameter is the name of the function but afaik it is optional (it can be left blank or omitted at all).

pp();
function pp()
{
for(j=0;j<=11;j++)
{
if(j%4==0)
{
html+= "<br>";
}
html += "<span class='remote' onclick='setLift(this)' >"+ j+"</span>";
}
document.getElementById('el').innerHTML = html;
}
function setLift(x)
{
alert(x.innerHTML);
}

Related

Why my Chrome extension event doesn't work?

I'm trying to create a chrome extension. I had a problem with the affectation of event for the new element that i append to the dom of site with content. Js
If I add an event to an element' 'for example class' exist already in the page, it works correctly. Just for my new appended element((in the code iadded a button ,the event is just an alert to test))
function tst() {
myclass = $("._3hg-._42ft");
myclass = myclass.not(".supp");
myclass.addClass("supp");
var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
for (i = 0; i < myclass.length; i++) {
result = patt.exec(myclass[i]);
myclass.append('<button class="fact" id=' + result[0] + ' style="position: absolute;">fact</button>');
};
/* this is a simple event*/
/***********************/
$(".fact").on('click', function() {
alert("no event work ");
});
Making somewhat broad assumption here in my answer that it is JavaScript/jQuery related and is NOT an extension...or is so still in that context.
You need to attach the event to the container here perhaps for the dynamically created elements. Lots of global stuff, suggested to not do that, updated there.
Appends a lot of buttons perhaps? might need to only hit DOM once but left as-is in this isolated function.
function tst() {
let myclass = $("._3hg-._42ft")
.not(".supp");
myclass.addClass("supp");
//let result = {};
var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
var i = 0; //avoid global
for (i; i < myclass.length; i++) {
// broad assumption of the returned value from patt.exec() here
// not even sure why it needs an id, have a class, use for css
let result = patt.exec(myclass[i]);
myclass.append('<button class="fact" id="' + result[0] + '">fact</button>');
}
/* attache event to pre-existing element */
/***********************/
myclass.on('click', ".fact", function() {
alert("event works");
});
}
button.fact {
position: absolute;
}

javascript: set onclick function with a parameter for a button

I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.
var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(i = 0; i < audioMp3.length; i++{
var audioBtn = document.createElement("BUTTON");
audioBtn.setAttribute("onclick", "playAudio(i);";
}
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(var i = 0; i < audioMp3.length; i++){
var node = document.createElement("BUTTON");
var textnode = document.createTextNode(audioMp3[i]);
node.appendChild(textnode);
node.setAttribute("onclick", "playAudio("+i+");");
document.getElementById("element").appendChild(node);
}
function playAudio(i){
alert(i);
}
<div id="element"></div>
I'm pretty sure that this should work :
audioBtn.setAttribute("onclick", "playAudio("+i+");");
audioBtn.onclick = function(){
playAudio(i)
}
Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.
I don't know your precise code but that is the pseudo-code to do it.

Looping inside jQuery function only issue

I'm having some trouble with jQuery in Meteor - I'm just trying to learn so I hope someone could help.
So when #addButton is clicked it will append the div to the .formField and each div created on click will have an unique class, eg formField[1], formField[2] etc
The trouble is when the button is clicked instead of just changing the name of the div only, the div is also added 50 times. I know how dumb it sounds as its a loop, but how would I loop only the div's class on click so each have a different name?
My code is below:
Template.form.events({
'click #addButton': function(event) {
var i;
for (i = 0; i < 50; i++) {
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
return false;
If I understand what you are doing here you don't need a loop. You just need a variable to increment every time the button is clicked. Take your append out of the loop and instead on click increment your variable by one then call an append. No loop necessary.
var i = 0;
Template.form.events({
'click #addButton': function(event) {
i += 1;
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
});
return false;
Do it like this, (i.e. by creating a closure), click run to verify
var uuid = 0;
$('#addButton').on('click', function (event) {
uuid = uuid + 1;
$(".formField").append('<div class="formField[' + uuid + ']">Form' + uuid + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formField"></div>
<input type="button" value="Add New" id="addButton"></input>

List of generated event listeners only triggers last one

Here is the full code for demonstration: http://jsfiddle.net/DF2Uw/4/
Basically, I generate multiple event listeners with a FOR loop. I generate multiple <selects> and want to detect the onChange event and return the ID of the specific select that was changed. However it seems only the last eventlistener survives as the others do no trigger.
Any explanation for this behavior?
HTML
<ol id="slots"></ol>
JAVASCRIPT
var slotnameHtml = '';
for (var i = 0; i < 3; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option></optgroup>';
slottime.id='test'+i;
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
slottime.addEventListener('change', function () {
alert(slottime.id)
});;
}
That's because the handlers you bind to change do not run immediately, but later. In the meantime, your for loop has run its course and slottime has been rebound to its final value (the last <select> element you created). All the handlers will only see that value.
You can introduce a closure in order for the right elements to be accessible to the handlers:
document.getElementById("slots").appendChild(slotlist);
(function(slottime) {
slottime.addEventListener("change", function() {
alert(slottime.id);
});
})(slottime);
As Teemu righfully says in the comments, the simplest solution is to take advantage of the fact that this is bound to the target element inside the handler:
slottime.addEventListener("change", function() {
alert(this.id);
});
You have to use the following alert parameter insted:
alert(this.getAttribute('id'));

Remove onclick event from img tag

Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??
document.getElementById('cmdt_1_1i').removeAttribute("onclick");
var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}
Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';
try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);
If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.
You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.

Categories