sorry am still learning JavaScript, read W3Cschools javascript and Jquery but there is a lot they don't teach.
I am studying animation at the moment, how do I auto start this rather then wait for someone to click (event listener), I've attempted turning it into a function but I must be doing it wrong, also 1 more what does (Idx) mean, I understand (id) is Html ID element but not sure Idx, not easy to find on google. to read, event listener starts at 5th line from the bottom, and the shuffle cards is 6th line from top (not sure if that helps), original code is located here http://www.the-art-of-web.com/javascript/css-animation/ thanks for any help.
Regards. William.
var cardClick = function(id)
{
if(started) {
showCard(id);
} else {
// shuffle and deal cards
card_value.sort(function() { return Math.round(Math.random()) - 0.5; });
for(i=0; i < 16; i++) {
(function(idx) {
setTimeout(function() { moveToPlace(idx); }, idx * 100);
})(i);
}
started = true;
}
};
// initialise
var stage = document.getElementById(targetId);
var felt = document.createElement("div");
felt.id = "felt";
stage.appendChild(felt);
// template for card
var card = document.createElement("div");
card.innerHTML = "<img src=\"/images/cards/back.png\">";
for(var i=0; i < 16; i++) {
var newCard = card.cloneNode(true);
newCard.fromtop = 15 + 120 * Math.floor(i/4);
newCard.fromleft = 70 + 100 * (i%4);
(function(idx) {
newCard.addEventListener("click", function() { cardClick(idx); }, false);
})(i);
felt.appendChild(newCard);
cards.push(newCard);
I've gone through your code and added comments to try and help explain what is going on in this file:
//Declare card click function. Takes one parameter (id)
var cardClick = function(id){
if(started) {
showCard(id);
} else {
// shuffle and deal cards
card_value.sort(function() {
return Math.round(Math.random()) - 0.5;
});
for(i=0; i < 16; i++) {
(function(idx) {
setTimeout(function() {
moveToPlace(idx);
}, idx * 100);
})(i);
}
started = true;
}
};
// initialise
//set stage as reference to some element
var stage = document.getElementById(targetId);
//append a div with ID "felt" to the stage element
var felt = document.createElement("div");
felt.id = "felt";
stage.appendChild(felt);
// template for card
//declare card variable as a div with some html content
var card = document.createElement("div");
card.innerHTML = "<img src=\"/images/cards/back.png\">";
//Loop from 0 to 16, where i = current value
for(var i=0; i < 16; i++) {
//create a copy of the card made earlier
var newCard = card.cloneNode(true);
//apply some attributes to the new card
newCard.fromtop = 15 + 120 * Math.floor(i/4);
newCard.fromleft = 70 + 100 * (i%4);
//Create and run an anonymous function.
//The function takes one parameter (idx)
//The function is called using (i) as (idx)
(function(idx) {
//add click handler to the card element that triggers the card click
//function with parameter (idx)
newCard.addEventListener("click", function() { cardClick(idx); }, false);
})(i);
//add new card to the stage
felt.appendChild(newCard);
//add new card to an array of cards
cards.push(newCard);
} //end for loop (I added this. It should be here)
how do I auto start this rather then wait for someone to click
The way I would do it, is add a manual click event after the for loop that targets the first card that has the event handler. Because there is no ID set on the cards, I would try using the array that the cards are added to. Assuming that the cards array was empty when we started:
cards[0].click();
If that doesn't work, I would try targeting the item in the DOM. We know that each card is added to the end of div#felt. So, if we can target the first div inside felt, we should be able to trigger the click event on it.
document.getElementByID("felt").firstChild.click();
what does (Idx) mean
I'm hoping the comments help explain this. It looks like the variable idx is just used as an extended reference of i. Inside a for loop, the writer creates a function that takes one parameter (idx). The for loop has a variable (i) that increases by one for each instance of the loop. Each time the loop happens, i is passed into function as idx.
I hope that helps to get you an understanding of how this code works.
Related
Backstory:
• Varying dynamic items (buttons) will be generated and displayed in a single div.
• Each button is created from a unique object with a unique ID value.
Problem:
How do I get each generated and displayed button to retain, and then pass along when clicked, its unique "id"?
All of my efforts so far have gotten me results of "undefined" or displaying only the last generated id value, regardless of what button is clicked. Also things that target DOM elements don't seem to help as each of my unique items will not be inside it's own element. Rather just listed out in a single element.
As far as ideas/answers I am after straightforward/readability vs. speed/efficiency. I am also trying to keep as much of my functionality on the javascript side and rely on HTML for as little as possible beyond "displaying" things.
The following code is working as expected for me sans my question:
var allItems = [
{id:1, name:"Space Gem", power:100},
{id:14, name:"Time Gem", power:200},
{id:22, name:"Reality Gem", power:300}
];
var map = {
tile: [
{id:22},
{id:1}
]
}
onTile();
function onTile() {
for ( var i = 0; i < map.tile.length; i++ ) {
var itemId = map.tile[i].id;
for (var j = 0; j < allItems.length; j++) {
if (itemId === allItems[j].id) {
var itemName = allItems[j].name;
var button = document.createElement("button");
button.innerHTML = itemId + " " + itemName;
document.getElementById("tile_display").appendChild(button);
button.addEventListener ("click", get, false);
}
}
}
}
function get(itemId) {
alert ("You clicked button with ID: " + itemId);
}
The only problem I see is that you are passing the same event listener to each newly-created button. And what is more, you are passing the get function but not specifying an argument - which means that itemId will always be undefined when the function runs in response to a click. (I realise now this isn't true - itemId instead will refer to the Event object corresponding to the click event that's just happened - but this is no use to you in this case.)
So all you need to do, I think, is change:
button.addEventListener ("click", get, false);
to:
button.addEventListener ("click", function() {get(itemId);}, false);
EDIT: so this solves the "undefined" problem. But as you noticed, you are getting "id: 1" for both buttons. This is due to the fact that the event listener is a "closure" over its enclosing scope, which here is the onTile function. This means that, when you click the button and the event listener runs, it looks up the value of itemId, which it still has access to even though that scope would otherwise have been destroyed. But there is only one itemId in that scope, and it has whichever value it had when the function finished executing (here 1) - the same value for each event listener.
The simplest fix by far, assuming you are running in ES6-supporting browsers (which these days is all of them, although it always amazes me how many are still using IE which doesn't support it), is simply to change var ItemId = ... to let ItemId = .... Doing this gives ItemId a new scope, that of the loop itself - so you get a different value "captured" each time through the loop - exactly as you want.
In case you do need to support pre-ES6 browsers, you can perform the same "trick" without let, by enclosing the whole body of the outer for loop in a function (this creates a new scope each time), and then immediately invoking it, like this:
function onTile() {
for ( var i = 0; i < map.tile.length; i++ ) {
(function() {
var itemId = map.tile[i].id;
for (var j = 0; j < allItems.length; j++) {
if (itemId === allItems[j].id) {
var itemName = allItems[j].name;
var button = document.createElement("button");
button.innerHTML = itemId + " " + itemName;
document.getElementById("tile_display").appendChild(button);
button.addEventListener ("click", function()
{get(itemId);},
false);
}
}
})();
}
}
function get(itemId) {
alert ("You clicked button with ID: " + itemId);
}
Javascript closures, and in particular how they interact with loops like this, are a tricky topic which has caught many out - so there are loads of SO posts about it. JavaScript closure inside loops – simple practical example is an example, with the answer by woojoo66 being a particularly good explanation.
All that ever needs to happen here is to use the onClick = function() {} property for the newly created button and directly specify the itemId there like so:
button.onclick = function() {
get(itemId);
}
You can easily implement this in a little function like make_button(itemId) { } (see below)
make_button(1);
make_button(2);
make_button(3);
make_button(4);
make_button(5);
function make_button(itemId) {
var button = document.createElement("button");
button.onclick = function() {
get(itemId);
}
button.innerHTML = "button " + itemId;
document.getElementById("mydiv").appendChild(button);
}
function get(_itemId) {
alert("You picked button " + _itemId);
}
<div id="mydiv">
</div>
A much easier way to do this would be to do something like this:
var allItems = [{
id: 1,
name: "Space Gem",
power: 100
},
{
id: 14,
name: "Time Gem",
power: 200
},
{
id: 22,
name: "Reality Gem",
power: 300
}
];
var map = {
tile: [{
id: 22
},
{
id: 1
}
]
}
onTile();
function onTile() {
for (var i = 0; i < map.tile.length; i++) {
var itemId = map.tile[i].id;
/* filter out only items in allItems[] that have id === itemId */
var items = allItems.filter(item => item.id === itemId);
/* loop through those few items and run function make_button */
items.forEach(function(item) {
make_button(item.id, item.name);
});
}
}
/* avoid the use of function names such as 'get' 'set' and other commonly used names as they may conflict with other scripts or native javascript */
function make_button(itemId, itemName) {
var button = document.createElement("button");
button.innerHTML = itemId + " " + itemName;
button.onclick = function() {
get_clicked_tile(itemId); // changed name from 'get'
};
document.getElementById("tile_display").appendChild(button);
}
function get_clicked_tile(itemId) {
alert("You clicked button with ID: " + itemId);
}
<div id="tile_display"></div>
In a game I want to add the numbers 1-9 that are draggable, and on the drag and drop events I want to call some functions. But in a loop events are not working. Any solution will be nice.
Here is the code:
var count = 0;
points.forEach(function(item){
var one = game.add.text(item.centerX, item.centerY, count, this.style);
one.anchor.setTo(0.5)
one.inputEnabled = true;
one.input.enableDrag();
one.input.startDrag(game.input.activePointer);
one.events.onInputDown.add(this.clone, this, 0, one);
one.events.onDragStop.add(this.fixLocation);
count++;
});
This gives me the error:
Phaser.Signal: listener is a required param of add() and should be a Function.
this is the fixlocation function
fixLocation: function(item){
if(rectangle.contains(item.x, item.y)){
itemAdded += 1;
} else{
item.destroy()
}
},
My fault. Acutally the this inside foreach in in wrong context. It is the inside of the loop. All i have to do was to call function outside of the loop. that is:
var count = 0;
var me = this;// get this here
points.forEach(function(item){
var one = game.add.text(item.centerX, item.centerY, count, this.style);
one.anchor.setTo(0.5)
one.inputEnabled = true;
one.input.enableDrag();
one.input.startDrag(game.input.activePointer);
one.events.onInputDown.add(me.clone, this, 0, one); // now call the function
one.events.onDragStop.add(me.fixLocation);
count++;
})
I'm building an internal Javascript app and it has a function for creating editable lists of objects. It loops through an array of objects, and displays a summary for each one along with an edit button. It then displays some more buttons at the bottom of the list for creating new items and going to the previous screen.
All of the buttons work, expect ones created within the loop. The click event never fires for the buttons added to the DOM within the loop. The really strange thing is that if I take the edit variable and append to the DOM outside of the loop the click event does fire.
var displayArray = function (where, list, summarise, display, newItem, completion, back) {
var listing = $("<div>");
listing.addClass("Listing");
for (var i = 0; i < list.length; i++) {
var index = i;
var edit = createButton("Edit", function () {
display(list[index]);
});
var anchor = $("<p>");
anchor.text(summarise(list[index]));
anchor.append(edit); //this will create an edit button, but the click event is never fired
listing.append(anchor);
}
where.append(listing);
var create = createButton("New", newItem);
where.empty();
where.append(listing);
where.append(create);
//where.append(edit); // uncomment this and it will create a button that will display the last item in the list
if (back) { where.append(createButton("Back", back)); }
if (completion) {
completion();
}
}
var createButton = function(name, action){
var button = $("<input>");
button.attr("type", "button");
button.attr("value", name);
button.on("click", action);
return button;
}
The variables being passed into the function are as follows:
where = the html element that will display the items
list = the array of objects to display
summarise = a function that generates summary text for an object passed to it that will be displayed for this object listing
display = a function that generates the edit screen for an object
newItem = a function that generates a new object and displays the edit screen for it
completion = a function to call after the screen has been built that will generate any additional UI as needed.
back = a function to display the previous screen
The behaviour is consistent across IE9, Firefox 20.0.1, and Chrome 29.0.1547.66
I know exactly what the problem is here:
Try this.
for (var i = 0; i < list.length; i++) {
var index = i;
var edit = createButton("Edit", (function (item) {
return function () {
display(item);
};
})(list[index]));
I have an array of objects (specifically easelJS images) - something like this:
var imageArray = new Array;
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape);
What I want to do is have an event listener instead of:
gShape.addEventListener("click", function() {alert"stuff"});
I want the program to know specifically which region is clicked so that I can send an alert box in the following way:
imageArray[index].addEventListener("click", function(){
alert " you clicked region number " + index}
Sure. You can just use a closure to save the index of that iteration. Otherwise there are shared by the same function scope and will give you the value of the same iteration. Creating a separate function for each will save the state of that inside the function.
var imageArray = new Array;
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape); // Dumped all the objects
for (var i = 0; i < imageArray.length; i++) {
(function(index) {
imageArray[index].addEventListener("click", function() {
console.log("you clicked region number " + index);
})
})(i);
}
or better
for(var i = 0; i < imageArray.length; i++) {
imageArray[i].addEventListener("click", bindClick(i));
}
function bindClick(i) {
return function() {
console.log("you clicked region number " + i);
};
}
ES6 to the rescue
let imageArray = [];
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape); // Dumped all the objects
for (let i = 0; i < imageArray.length; i++) {
imageArray[i].addEventListener("click", function() {
console.log("you clicked region number " + i);
});
}
Using the let keyword creates a block scoping for the variable in iteration and will have the correct index when the event handler is invoked.
Something like this should work:
for (var i = 0 ; i < imageArray.length ; ++i) {
function(index) {
imageArray[index].addEventListener("click", function() {
alert ("You clicked region number: " + index");
});
} ( i);
}
The reason it works is because it creates a closure that holds the value of index that will be shown in the alert message. Each time through the loop creates another closure holding another value of index.
//gShape must be an array of HTMLElement
gShape.forEach(element => element.addEventListener("click", function () {
// this, refers to the current element.
alert ("You clicked region number: " + this.getAttribute('data-region'));
}));
Sure, a closure is the solution, but since he's got Ext loaded he might as well use it and get some very readable code. The index is passed as the second argument to Ext.Array.each (aliased to Ext.each).
Ext.each(imageArray, function(gShape, index) {
gShape.addEventListener("click", function() {
alert("You clicked region number " + index);
});
});
This is what I'm using for div id's:
var array = ['all', 'what', 'you', 'want'];
function fName () {
for (var i = 0; i < array.length; i++)
document.getElementById(array[i]).addEventListener('click', eventFunction);
};
Good Luck!
A simple way to do this, is by calling a querySelectorAll() on all
the elements and using a loop to iterate and execute a function with the data of that specific array index once the EventListener is
triggered by the element clicked.
Snippet
Retrieving the id attribute of the clicked element
document.querySelectorAll('li').forEach(element => {
element.addEventListener('click', () => {
console.log(element.getAttribute('id'))
})
})
li{cursor:pointer}
<ul>
<li id="id-one">One</li>
<li id="id-two">Two</li>
<li id="id-three">Three</li>
<li id="id-four">Four</li>
</ul>
I am having trouble with JS closures:
// arg: an array of strings. each string is a mentioned user.
// fills in the list of mentioned users. Click on a mentioned user's name causes the page to load that user's info.
function fillInMentioned(mentions) {
var mentionList = document.getElementById("mention-list");
mentionList.innerHTML = "";
for (var i = 0; i < mentions.length; i++) {
var newAnchor = document.createElement("a");
// cause the page to load info for this screen name
newAnchor.onclick = function () { loadUsernameInfo(mentions[i]) };
// give this anchor the necessary content
newAnchor.innerHTML = mentions[i];
var newListItem = document.createElement("li");
newListItem.appendChild(newAnchor);
mentionList.appendChild(newListItem);
}
document.getElementById("mentions").setAttribute("class", ""); // unhide. hacky hack hack.
}
Unfortunately, clicking on one of these anchor tags results in a call like this:
loadUserNameInfo(undefined);
Why is this? My goal is an anchor like this:
<a onclick="loadUserNameInfo(someguy)">someguy</a>
How can I produce this?
Update This works:
newAnchor.onclick = function () { loadUsernameInfo(this.innerHTML) };
newAnchor.innerHTML = mentions[i];
The "i" reference inside the closure for the onclick handlers is trapping a live reference to "i". It gets updated for every loop, which affects all the closures created so far as well. When your while loop ends, "i" is just past the end of the mentions array, so mentions[i] == undefined for all of them.
Do this:
newAnchor.onclick = (function(idx) {
return function () { loadUsernameInfo(mentions[idx]) };
})(i);
to force the "i" to lock into a value idx inside the closure.
Your iterator i is stored as a reference, not as a value and so, as it is changed outside the closure, all the references to it are changing.
try this
function fillInMentioned(mentions) {
var mentionList = document.getElementById("mention-list");
mentionList.innerHTML = "";
for (var i = 0; i < mentions.length; i++) {
var newAnchor = document.createElement("a");
// Set the index as a property of the object
newAnchor.idx = i;
newAnchor.onclick = function () {
// Now use the property of the current object
loadUsernameInfo(mentions[this.idx])
};
// give this anchor the necessary content
newAnchor.innerHTML = mentions[i];
var newListItem = document.createElement("li");
newListItem.appendChild(newAnchor);
mentionList.appendChild(newListItem);
}
document.getElementById("mentions").setAttribute("class", "");
}