Search code examples
jqueryloopsfor-loopbindunbind

Iterate through array and bind events


I've checked through the forum and cant seem to find a solution to my problem.

I have an array of id's and I'm iterating through them with a for loop adding mouse events for enter and leave. However the events all bind to the final ID, which is probably a for each issue.

I've put it up on a fiddle below, any help would be appreciated - my brain is a bit frazzled today.

http://jsfiddle.net/shanemccster/e48vu/4/

cards = new Array('#box0','#box1','#box2');
function bindCardEvents(){
    for (var i=0; i<cards.length; i++){
        var targetID = '#'+$(cards[i]).attr('id');
        $(targetID)
            .mouseenter(function() {
                TweenMax.to(targetID,0.3, {opacity:0.5} )
            }).mouseleave(function() {
                TweenMax.to(targetID,0.3, {opacity:1}) 
            }); 
    }
}
bindCardEvents();

Thanks


Solution

  • jsFiddle Demo

    You can just join the ids together with , which by convention adds the selectors to a set in jQuery. After doing that, you can assign the event to the set returned by those selectors. Each event will have access to the current element this. TweenMax.to expects a selector or an element, so you can pass this into the function without manually constructing an id selector.

    var cards = new Array('#box0','#box1','#box2');
    var cardSelector = cards.join(",");
    function bindCardEvents(){
      $(cardSelector).mouseenter(function() {
        TweenMax.to(this,0.3, {opacity:0.5} )
      }).mouseleave(function() {
        TweenMax.to(this,0.3, {opacity:1}) 
      });
    }
    bindCardEvents();
    

    For brevity this will also work

    $(cards.join(",")).mouseenter(function() {
        TweenMax.to(this,0.3, {opacity:0.5} )
      }).mouseleave(function() {
        TweenMax.to(this,0.3, {opacity:1}) 
    });