The following script:
var containerDIV = document.getElementById("sampleContainer");
for(var i = 0; i < 5; i++)
{
var dynamicDIV = document.createElement("div");
containerDIV.appendChild(dynamicDIV);
dynamicDIV.onclick = function() { alert(i); };
dynamicDIV.innerHTML = "Row: " + i;
}
when clicking on the dynamically rows the output in the alert box will always be "5" instead of 0, 1, ..
Do anyone knows a proper way to assign the onclick event?
You should use the closure power:
for (var i = 0; i < 5; i++) {
(function(i) {
dynamicDIV.onclick = function() {
alert(i);
};
})(i);
}
DEMO: http://jsfiddle.net/zvPfZ/
Related
function albumCoverDisplay() {
var i = 0;
for (i = 0; i < albumCover.length; i++) {
albumCover[i].addEventListener("click", function() {
for (var i = 0; i < albumCover.length; i++) {
albumInfo[i].style.display = "none";
}
albumInfo[i].style.display = "block";
});
}
}
Looks like you want to be able to hide other albumCover elements on clicking one of them.
There are a couple of mistakes
Your inner for-loop re-localize the scope of i, use different variable
i's value (assuming another variable is used in inner for-loop) will not remain same when the click will happen.
Make it
function albumCoverDisplay()
{
for (let i = 0; i < albumCover.length; i++) //use let instead of var
{
albumCover[i].addEventListener("click", function() {
for (var j = 0; j < albumCover.length; j++)
{
albumInfo[j].style.display = "none";
}
albumInfo[i].style.display = "block";
});
}
}
I'm trying to create a tabbed interface in Javascript which will allow a user to click on a button atop each interface in order to make the div under it become active while the other 'tabs'/divs recede to the background. I'm not quite sure I got that out right so attached is a screenshot of what I'm trying to make:
My code attaches one button -- beside the first div-- instead of all three and returns an error that says nodeChildren[j].getAttribute("data-tabname") is not a function although as far as I know, it seems it is.
I'll post my JavaScript code then add a link to fiddle where everything is.
function asTabs(node) {
var button = document.createElement("BUTTON");
var tempArray = [];
var nodeChildren = Array.prototype.slice.call(node.childNodes);
nodeChildren.filter(function(){
for (var i = 0; i < nodeChildren.length; i++) {
if (nodeChildren[i].nodeType === 1) {
tempArray += nodeChildren[i];
return tempArray;
}
}
});
nodeChildren.forEach(function (){
for (var j = 0; j < nodeChildren.length; j++) {
node.insertBefore(button, nodeChildren[j]);
var buttons = document.getElementsByTagName("button");
for (var k = 0; k < buttons.length; k++) {
buttons[k].innerHTML = nodeChildren[j].getAttribute("data-tabname").textContent;
}
}
});
var hide = nodeChildren.slice(1);
for (var l = 0; l < hide.length; l++) {
hide[l].className = "hide";
}
buttons[k].addEventListener("click", function (){
if (nodeChildren[j].className = "") {
nodeChildren[j].className = "hide";
}
else nodeChildren[j].className = "";
});
}
asTabs(document.querySelector("#wrapper"));
Then here's my fiddle containing comments explaining what is being tried to achieve on each line
https://jsfiddle.net/nmeri17/nmswdota/
Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.
I'm trying to assign onmouseover - onmouseout events to an array of divs with a loop.
I created the divs through a loop as well using a function parameter createDivs(x), x being number of divs and a bunch of this.property to assign styles.
Everything is working as expected, but assigning the mouse events through a loop with the divArray.Length object.
The script is the following:
Making the divs:
containers : {
create : function(containerCount){
var cArray = [this.c1Color,this.c2Color,this.c3Color];
var aCounter = 0;
divArray = [];
for (var i = 1; i <= containerCount; i++){
var c = document.createElement("div");
c.id = ("container"+i);
c.style.width = "100%";
c.style.height = (this.height) + "px";
c.style.backgroundColor = (cArray[aCounter]);
aCounter++;
document.body.appendChild(c);
divArray.push(c);
}
}
},
Assigning the Events:
events : {
on : function () {
var z = 1;
for (var i = 0; i < divArray.length; i++){
var cont = ("container" + z);
document.getElementById(divArray[i].id).onmouseover = function(){
gala.animate.openAnimation(cont);
}
document.getElementById(divArray[i].id).onmouseout = function(){
gala.animate.shrinkAnimation(cont);
}
console.log(cont);
z++;
}
}
The console show the array sort through the number of divs as expected, and the cont variable ++ increase to assign the id. However at the end, the event listeners are only applied to the last element of the array.
Btw the cont variable is just a placeholder for a parameter that passes too the animation method so it knows what div to animate, meaning animat.openAnimation(cont) cont = div name.
Looks like you need a new scope to keep the value of the cont variable constant inside the event handlers. I replaced the cont variable as it didn't really seem neccessary
events : {
on : function () {
for (var j = 0; j < divArray.length; j++){
(function(i) {
divArray[i].onmouseover = function(){
gala.animate.openAnimation("container" + (i+1));
}
divArray[i].onmouseout = function(){
gala.animate.shrinkAnimation("container" + (i+1));
}
})(j);
}
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
The following code creates 10 elements under <body id="container" />. When i click on any element, I always see an alert with the value 10.
How can I get each alert to show the index of each element?
for (var i = 0; i < 10; ++i) {
var id = "#element_" + i;
$("#container").append('<p id="element_' + i + '">foo</p>');
$(id).click(function (e) {
alert(i);
});
}
You need either closure or simply use $.on() with data:
for (var i = 0; i < 10; ++i) {
var id = "#element_" + i;
$("#container").append('<p id="element_' + i + '">foo</p>');
$(id).on("click", i, function (e) { alert(e.data); });
}
Don't make functions inside for loops
for (var i = 0; i < 10; ++i) {
$("#container").append('<p id="element_' + i + '">foo</p>');
}
$("#container > p").click(function (e) {
var idNum = this.id.split('_')[1];
alert(idNum); // 0, 1, 2 ...
});
DEMO
need to create a private closure
for (var i = 0; i < 10; ++i) {
(function(idx){
var id = "#element_" + idx;
$("#container").append('<p id="element_' + idx + '">foo</p>');
$(id).click(function (e) {
alert(idx);
});
})(i)
}
Demo: Plunker