Trying to create an array to target objects for animation - javascript

I have maps of districts named mc_1, mc_2, mc_3 etc...
I'm triggering an event when mouse hovers over them. Instead of writing code for each mc_n I thought I could use arrays. But I havent done that before.
Currently I have
var district = [];
for (var i = 0; i <= 20; ++i) {
district[i] = "mc_" + i;
}
stage.enableMouseOver(3);
this.district[i].on('mouseover', function(){
this.district[i].gotoAndPlay(2);
});

After the for loop, there is no more i variable, instead you can use forEach:
var district = [];
for (var i = 0; i <= 20; ++i) {
district[i] = document.getElementById("mc_" + i); // get the DOM elements by ID
}
stage.enableMouseOver(3);
this.district.forEach( (el) => { // loop through the DOM elements
el.on('mouseover', function(){ // add the muoseover event to the current element
el.gotoAndPlay(2);
});
});
But if you want to apply the same behavior to all of those elements, i would suggest to use CSS classes in order to identify them.

Related

Access clone containers produced by FOR LOOP

I have a container and i have cloned it to create 3 more containers. The main reason i used the Clone property was because i didnt want to rewrite the code again and again to make the same containers. Now i want to update different data for the cloned containers. I have managed to pass the heading name for the original container as you can see in the code. Now how do I access my cloned containers and change the data in them. I have put the code which i tried below (failed). When i put data[1],data[0] etc, nothing gets updated.
Current JavaScript
$(document).ready(function() {
var e = $('.column'); //column is the class which contains the container
for (var i = 0; i < 3; i++) {
e.clone().insertAfter(e);
}
document.getElementById("heading").innerHTML = ("TRAILER 22");
Failed Javascript , this does not update anything on the webpage.
$(document).ready(function() {
var e = $('.column');
for (var i = 0; i < 3; i++) {
e.clone().insertAfter(e);
}
var data = document.querySelectorAll(".column");
data[1].document.getElementById("heading").innerHTML = ("TRUCK 22");
});
You try to do a document call on a element, that is not possible. If you want to change the first column (i switched the code to jQuery, what makes it a lot easier):
$(document).ready(function() {
var e = $('.column');
for (var i = 0; i < 3; i++) {
e.clone().insertAfter(e);
}
var data = $(document).find(".column:first-of-type");
data.html("TRUCK 22");
});

how to create more than one element in the DOM with js using a for loop?

Well, the result I want to get is my div element should have the same numbers of p elements as the array.
In order to do this, I tried using a for loop but it just create one p element, so I didn't work.
Anyone have idea how to do this? (I'm just learning js).
const diccionario = () => {
var dama = ["bird:pajaro", "car:carro", "house:csa", "camis"];
document.getElementById("dic").addEventListener("click", () => {
var pes = document.createElement("p");
for(var i = 0; i < dama.length; i++){
pes.innerHTML = dama[i];
document.getElementById("cuadro").appendChild(pes);
}
})
}
You need to create the element inside the loop. If you create it outside the loop, then when you call appendChild, it will get removed from wherever it was previously in the DOM:
const diccionario = () => {
var dama = ["bird:pajaro", "car:carro", "house:csa", "camis"];
document.getElementById("dic").addEventListener("click", () => {
for(var i = 0; i < dama.length; i++){
var pes = document.createElement("p"); // <----------------
pes.innerHTML = dama[i];
document.getElementById("cuadro").appendChild(pes);
}
})
}
appendChild doesn't create a copy of the existing element - rather, it just appends the existing element.

converting JS array with objects to HTML collection

I got to the point with my project where I decided to simplify some of the js functions where I am looking for a parent in a DOM tree, then drill down to the elements many many times in one function. instead I though I will make instances of a function which will keep some data so then I can refer and operate on objects in easy way. I got it working but as I was going along, I decided to extend functionality and add some extra functions like getElementsByClassNameThenTagName.
I loop through the arrays and if add matching elements to the array.
I have noticed (sadly only now) that I am creating an array with elements rather than HTML collection. As a results, I cannot refer to the objects in my findings by typing buttons['reset'].disabled = false;. I can access my reset button by buttons[3].disabled = false; but this would cause a lot of inconvenience.
I am therefore looking for a way to convert my array with object into a HTML collection.
Please see below my current function:
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = [];
var regexStr = elementClass;
var regex = new RegExp(regexStr);
var x = moduleNode.getElementsByClassName(elementClass);
// console.log(x);
var y;
for ( var i = 0; i < x.length; i++ ) {
// console.log(i);
y = x[i].getElementsByTagName(elementTag);
// console.log(y);
for (var k=0; k<y.length; k++){
// console.log(y[k]);
results.push(y[k]);
}
// console.log(results);
}
return results;
};
Any suggestions please?
Thanks.
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = {}; // thid should be an object (collection)
var x = moduleNode.querySelectorAll("." + elementClass + " " + elementTag);
x.forEach(function(y) {
var name = y.getAttribute("name"); // if you really sure that all the matched elements have names
results[name] = y;
});
return results;
};
Now you can use the results array like this:
var someElement = results['some name'];
NOTE: All the matched elements x should have a name attribute, and all the name attributes of the matched elements should be unique.

obtaining all items of listView in winjs

I have a listview div on screen and I have added itemDataSource to it successfully
var lettersList = new WinJS.Binding.List(jsonArrayForClearance);
var list_ = document.getElementById("prodListView").winControl;
list_.itemDataSource = lettersList.dataSource;
list_.itemTemplate = document.getElementById("tileTemplate");
list_.forceLayout();
Now in each item I have added a custom input type for user to specify(using template). I want to iterate through all the items of list and obtain the value of that input type in an array.
how can I do it?
EDIT: My question is to access custom input type declared in list items. As such we use following code to access any input type named "inpT"
document.getElementById('inpT');
but how to access the same from list item? can I use Following code(as suggested by user2608614)
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
item.getElementById('inpT');
}
You can iterate through the list elements like this:
var listView = document.getElementById("prodListView").winControl;
listView.itemDataSource.getCount()
.done(function(count) {
for (var i = 0; i < count ; i++) {
listView.itemDataSource.itemFromIndex(i)
.done(function (item) {
//***item will contain your property
});
}
});
Is not the best solution as it make it difficult to chain the promises, I'm also looking for a better one. But it works.
Since you're using a Binding.List you can just iterate through that much like an array.
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
// do something with this item
}
The only thing to remember is that it doesn't support [] and instead you have to use .getAt() and .setAt().

Dynamically loading multiple <li>'s with a javascript for loop - nothing loading yet

I'm trying to load X amount of <li>'s into a <ul> via a for loop in a jquery function, and while I think I've got the syntax about right I'm not getting anything loading. (no problem with loading a single <li>, but none for multiples with the method I've tried)
Initially I attempted to pass a variable into the loop to determine the amount of increments: var peekListAmount = 5;
That didn't work so I went for a bog-standard loop incrementer. That doesn't work either so, after searching here and getting close, I have put together a fiddle to see if someone can point out what I'm doing wrong: http://jsfiddle.net/janowicz/hEjxP/8/
Ultimately I want to use Knockout.js to dynamically input a number to pass to the loop amount variable, but 1st things 1st.
Many thanks in advance.
When you do:
var peekListItem = $('<li>...</li>');
you're creating a single instance of an <li> node, encapsulated in a jQuery object.
Appending an already-present node to the DOM just removes it from its current place in the DOM tree, and moves it to the new place.
You need to create the node inside the loop, not outside, otherwise you're just re-appending the same node each time, not a copy of that node.
In fact, given you're not manipulating that node, you can just put the required HTML directly inside the .append() call without wrapping it in $(...) at all:
$(function() {
var peekList = $('<ul class="peekaboo-list">').appendTo('div.peekaboo-wrap');
function addLiAnchorNodes(nodeAmount) {
var html = '<li>' +
'<p class="peekaboo-text"></p></li>';
for (var i = 0; i < nodeAmount; ++i) {
peekList.append(html);
}
}
addLiAnchorNodes(5);
});
See http://jsfiddle.net/alnitak/8xvbY/
Here is you updated code
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
var peekListItem = '<li><p class="peekaboo-text"></p></li>';
//var peekListAmount = 5;
var tmp = '';
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
tmp += peekListItem;
}
peekList.append(tmp);
$('div.peekaboo-wrap').append(peekList); // This bit works fine
}
addLiAnchorNodes();
});
This should work. Instead of appending the list item in each loop, append the list only once at the end.
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
peekList.appendTo('div.peekaboo-wrap');
var addLiAnchorNodes = function (nodeAmount){
var list = "";
for (var i = 0; i < 10; i++){
list += '<li>Sample<p class="peekaboo-text"></p></li>';
}
peekList.append(list);
}
addLiAnchorNodes();
});
Here is the updated fiddle
Try this:
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
$(peekList).appendTo('div.peekaboo-wrap'); // This bit works fine
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
var peekListItem = $('<li><p class="peekaboo-text"></p></li>');
peekListItem.appendTo(peekList);
}
}
addLiAnchorNodes();
});

Categories