Setting onclick function to <li> element - javascript

I am trying to dynamically add onclick function to "li" tagged elements.
But the event does not fires.
Here is my code:
var arrSideNavButtons = [];
var sideNavLi = document.getElementsByClassName('side-nav')[0].getElementsByTagName('li');
var arrayOfSceneAudios = [scene1Audio, scene2Audio,...];
for (var i = 0; i < sideNavLi.length; i++) {
sideNavLi[i].onclick = function() {
arrayOfSceneAudios[i].play();
}
arrSideNavButtons.push(sideNavLi[i]);
}
Is it possible to code it this way?
If yes, what is my mistake?
Thanks a lot.

Wrap your onclick handler in a closure, else it only get assigned to the last elem in the loop:
for (var i = 0; i < sideNavLi.length; i++) {
(function(i) {
sideNavLi[i].onclick = function() {
arrayOfSceneAudios[i].play();
}
arrSideNavButtons.push(sideNavLi[i]);
})(i)
}

I think it's better to reuse one single function, instead of creating a new one at each iteration:
var arrSideNavButtons = [],
sideNavLi = document.getElementsByClassName('side-nav')[0].getElementsByTagName('li'),
arrayOfSceneAudios = [scene1Audio, scene2Audio,...],
handler = function() {
this.sceneAudio.play();
};
for (var i = 0; i < sideNavLi.length; i++) {
sideNavLi[i].sceneAudio = arrayOfSceneAudios[i];
sideNavLi[i].onclick = handler;
arrSideNavButtons.push(sideNavLi[i]);
}

Related

How to Change Color of Div within a for statement?

Inside my php while loop I output a div with id divborder, and class div-border
Inside that div i have another div with id title
<div id='divborder' class='div-border'>
<div id='Title'>This is Title</div> <br/> video elements
</div>
I have a JavaScript function that get called when the video ends
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
}
My Question is how do i change the border color of the div and the title of second div?
I can do it like this:
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
which works but its not dynamic
Save the value of value at i in another variable declared with let
for (var i = 0; i < videos.length; i++) {
let index = i; //save the value as let so that its binding stays
videos[i].addEventListener("ended", function(event)
{
var divBoader = document.querySelectorAll("div-border")[index];
divBoader.style.borderColor = "#b1ff99";
}
}
Or if the video elements are within the div-border, then use closest
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader = event.currentTarget.closest(".div-border");
divBoader.style.borderColor = "#b1ff99";
}
}
A little less verbose code
[...videos].forEach( s => s.closest( ".div-border" ).style.color = "#b1ff99" )
Try this,
Give class name div-border instead of divborder
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("div-border")[3];
divBoader2.style.borderColor = "#b1ff99";
}
What you need is probably a videos[i].parentNode instead of document.getElementsByClassName("div-border")[3] (see https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode)

Javascript Pass parameter to function inside variable

I'm trying to assign a click handler to a JQuery object, defined in a variable :
some.object.array[8].action = function(data){console.log(data);}
anotherobject = {..}
now inside some loop, I need to assign this function to the click handler:
and want to pass the whole 'anotherobject' object
for (var i = 0; i < foo.length; i++) {
$('<div/>').click(some.object.array[i].action);
}
But how can I pass the parameter?
If I encapsulate it inside some anonymous function, I'm losing my scope...:
for (var i = 0; i < foo.length; i++) {
$('<div/>').click(function() {
some.object.array[i].action(anotherobject)
});
}
because i has changed...
How are we supposed to do this?
There are just too many ways to do this:
for (var i = 0; i < foo.length; i++) {
(function(i) {
$('<div/>').click(function() {
some.object.array[i].action(anotherobject);
});
})(i);
}
Or
for (var i = 0; i < foo.length; i++) {
$('<div/>').data("i", i).click(function() {
var i = $(this).data("i");
some.object.array[i].action(anotherobject);
});
});
}
Or
function getClickHandler(callback, parameter) {
return function() { callback(parameter); };
};
for (var i = 0; i < foo.length; i++) {
$('<div/>').click(getClickHandler(some.object.array[i].action, anotherobject));
}
If you want your action function to maintain the div as this and still accept the jQuery event object, you can use bind like this example:
function action(another, event){
console.log(this, arguments);
}
$(function(){
for (var i = 0; i<10; i++) {
var anotherObject = "another"+i;
var div = $('<div>'+i+'</div>');
// force 'this' to be 'div.get(0)'
// and 'arg0' to be 'anotherObject'
div.click(action.bind(div.get(0),anotherObject));
$("body").append(div);
}
})
Example: https://jsfiddle.net/Lwe5b9cx/ You'll need to open the console to see the output, which should look like this:
for(var i = 0; i < foo.length; i++)
{
$('<div/>').click(
(
return function(callback){
callback(anotherobject)
}
)(some.object.array[i].action)
);
}

return or send variable to onchange event

I am trying to achieve the same functionality of a function from two separate events. So the function I created is:
function adding_stuff() {
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates
}
$(".primary .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(".primary .panel-content ul").append(li.concat(names[i]))
}
}
There are two buttons primary and secondary. I want the same functionality for both the functions but the output in different <div>. Currently the selected <div> is ".primary", however I want this to depend on the button which has been clicked.
The function is triggered using:
$("#primary").onchange = adding_stuff;
$("#secondary").onchange = adding_stuff;
NOTE: primary and secondary are inputs of type file.
You can add additional data when you register the callback, which will be made available within the event handler:
$('#primary').on('change', { target: '.primary' }, adding_stuff);
$('#secondary').on('change', { target: '.secondary' }, adding_stuff);
and then within the handler:
function adding_stuff(ev) {
var cls = ev.data.target; // extract the passed data
...
// file handling code omitted
$(".panel-content", cls).append(...)
}
using jquery's change() event
function adding_stuff(obj,objClass) {
var names = [];
var dates = [];
for(var i = 0; i < obj.files.length; i++) {
//adding stuff to names and dates
}
$("."+ objClass+" .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$("."+ objClass+" .panel-content ul").append(li.concat(names[i]))
}
}
$("#primary").change(function(){
adding_stuff(this,'primary');
});
$("#secondary").change(function(){
adding_stuff(this,'secondary');
});
Try
function adding_stuff(opselector) {
return function() {
var names = [];
var dates = [];
for (var i = 0; i < this.files.length; i++) {
// adding stuff to names and dates
}
var ul = $("<ul class='list-unstyled'></ul>").appendTo(opselector)
for (var i in names) {
ul.append("<li>" + li.concat(names[i]) + "</li>")
}
}
}
$("#primary").change(adding_stuff('.primary .panel-content'));
$("#secondary").change(adding_stuff('.secondary .panel-content'));
You can use $(this).attr("class") inside the function. It will return the class of button who triggered the event.
function adding_stuff() {
var div = $(this).attr("class");
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates to $div
}
$(div + " .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(div + " .panel-content ul").append(li.concat(names[i]));
}
}

Variable in wrong scope (maybe needs a closure?)

I have the following code that is in need of a closure:
var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
document.getElementsByClassName('l')[i].onclick = function (e){
preview(this.href, i);
};
}
What happens is that whenever an item is clicked, preview always the same number for i
I suspect what I need to do is
function indexClosure(i) {
return function(e) {
preview(this.href, i);
}
}
And assign the onclick's like this:
document.getElementsByClassName('l')[i].onclick = indexClosure(i);
But then this would no longer refer to my link... how is this problem solved?
Use closure to capture the counter of the cycle:
var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
(function(i){
document.getElementsByClassName('l')[i].onclick = function (e){
preview(this.href, i);
};
}(i))
}
doesn't onclick pass in (sender, eventArgs) allowing you to access this through sender?

Javascript for loop and alert

I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = alert(links[i].title);
}
}
What you were doing was actually running the alert function.
enclosing the whole thing in an anonymous function will only run it when it is clicked
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
alert(this.title);
}
}
You are assigning the onclick to the return value of alert(links[i].title); which doesn't make any sense, since onclick is supposed to be a function.
What you want instead is somethig like onclick = function(){ alert('Hi'); };
But
Since you are using a variable i in that loop you need to create a local copy of it
onclick = function(){ alert(links[i].title); }; would just use the outer scope i and all your links would alert the same message.
To fix this you need to write a function that localizes i and returns a new function specific to each link's own onclick:
onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
Final result:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
}
}
You can use jquery. To display title of the link on click.
$("#nav a").click(function() {
var title = $(this).attr('title');
alert(title);
});
links.forEach(function(link) {
link.onclick = function(event) {
alert(link.title);
};
}
Also note that your original solution suffered from this problem:
JavaScript closure inside loops – simple practical example
By passing in our iteration variable into a closure, we get to keep it. If we wrote the above using a for-loop, it would look like this:
// machinery needed to get the same effect as above
for (var i = 0; i < links.length; i++) {
(function(link){
link.onclick = function(event) {
alert(link.title);
}
})(links[i])
}
or
// machinery needed to get the same effect as above (version 2)
for (var i = 0; i < links.length; i++) {
(function(i){
links[i].onclick = function(event) {
alert(links[i].title);
}
})(i)
}
You need change .onclick for a eventlistener same:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click',function() {
alert(links[i].title);
},false);
}
}

Categories

Resources