Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple event listeners using a loop

Trying to create multiple listeners with a loop. How to make it work?

var buttons = ['one', 'two', 'tree'];
$.each(keys, function(key, value) {
    $(value).click(function() {
        // do something
    });
});

Also, is there a shortcut to not writing key, value when I only need the value?

like image 587
PyRoss Avatar asked May 13 '26 20:05

PyRoss


2 Answers

You are better off putting a delegated event listener on a parent instead of iterating through every button. For example, if you place all your <button> elements inside of a <div> with the id #container, then you can write your listener like this:

$('#container').on('click', 'button', function() {
  // do something;
});

Now, every time a button element is clicked within that div, your callback will be invoked. You can also use a class selector in place of 'button' to only listen to elements that have that class.

like image 185
pedrotp Avatar answered May 16 '26 09:05

pedrotp


If you want to make it work by looping then you can use

var buttons = ['.one', '.two', '.three'];

// ---------------- with -------- $.each();

$.each( buttons, function(key, value) {
    $(value).click(function() {
        // ------------- Do something
    });
});


// ------------------ with ----------- for loop


for( var i=0 ; i < buttons.length ; i++ )
{
    $(buttons[i]).click(function({
    // ------------- Do something
    });
}

But why to go this round if just want to assign event

$('.one, .two, .three, #one, #two, #three').click(function() {
     // ------------- Do something
});

OR if having variable

var buttons = '.one, .two, .three, #one, #two, #three';
$(buttons).click(function() {
     // ------------- Do something
});

AND THATS IT no key, no value, no for, no each

like image 37
kanudo Avatar answered May 16 '26 09:05

kanudo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!