3

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?

3
  • 1
    Place all your buttons in the DOM with common class and then simply attach the listener to that class as you are using jQuery Commented Feb 7, 2016 at 22:41
  • Unless your elements are XML-like <one> <two> etc... you're missing a key factor of assigning a class or Id like in: ['#one', '#two', '#three'] Commented Feb 7, 2016 at 23:36
  • Have you tried using a delegated event listener? If all the elements are invoking the same callback on the same event, there is no need to place a separate listener on each element. Commented Feb 8, 2016 at 5:56

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Sounds like you'd be better off assigning the click handler to a button with a specific class name instead of iterating over a list of selectors and assigning a new function inside a loop.

<button class='my-button' id="one">
  One
</button>
<button class='my-button' id="two">
  Two
</button>
<button class='my-button' id="three">
  Three
</button>

and the JS

$('.my-button').click(function() {
    var id = $(this).attr('id');
    $('body').append("<div>Button " + id + " was clicked</div>");
});

Take a look this fiddle https://jsfiddle.net/4e7rk10L/

Comments

0

In jQuery you can select some elements together, and seperate them using colon ,

var buttons = ['one', 'two', 'tree'];
$(buttons.join()).click(function(){
  // Do something
})

In this example I'm using join to convert the array to one,two,three then I add one event listener to all those element

3 Comments

Want this fire the event multiple times? Means if the array contains 3 values then the code inside the event listner will execute for three times.
It will fire want to for each click.
default for join() is a comma so don't even need the delimiter argument ... buttons.join() will do same
-1

If you really want loop (This was your question) you can do this:

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

5 Comments

Don't create functions inside loops. It's bad design.
Also note that function({ should be actually function() {
Sure. the I is defined out of scope. See how to solve it: jsbin.com/rumuzopobu/1/edit?html,css,js,output
I'd not write in any case code that might oddly result in unexpected behavior. The best way is following some clean code mindset. .join() (without the unneeded "," to the rescue - as in your first answer) since the $(selectors) will already be an jQ wrapper to an iterable collection of Elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.