Note that there are some explanatory texts on larger screens.

plurals
  1. PObind muiltiple elements to event handler using for loop in javascript
    primarykey
    data
    text
    <p>I found a way to bind single elements in an array with a for loop to event handlers in jQuery.</p> <p>This guide was useful to push me in that direction:<br> <a href="http://www.foliotek.com/devblog/keep-variable-state-between-event-binding-and-execution/" rel="nofollow">http://www.foliotek.com/devblog/keep-variable-state-between-event-binding-and-execution/</a></p> <p>Now I am one level deeper and I am trying to bind muiltiple elements with the same prefix in an array to event handlers in jQuery.</p> <h2>Here's what works:</h2> <pre><code>var menu=new Array("#power","#services","#cashback","#schedule"); $(document).ready(function(){ $(function() { for(var i in menu) { (function() { var x = menu[i]; var y = menu[i]+'_menu'; $(x).hover( function () { $(x).css({ backgroundColor: "#000", color: "#3ABCEF"}); $(y).show(); }, function () { $(x).css({ backgroundColor: "#333", color: "#FFF"}); $(y).hide(); } ); $(y).hover( function () { $(x).css({ backgroundColor: "#000", color: "#3ABCEF"}); $(y).show(); }, function () { $(x).css({ backgroundColor: "#333", color: "#FFF"}); $(y).hide(); } ); })(); } }); }); </code></pre> <h2>Here's what I really want:</h2> <pre><code>var menu=new Array("#power","#services","#cashback","#schedule"); $(document).ready(function(){ $(function() { for(var i in menu) { (function() { var x = menu[i]; var y = menu[i]+'_menu'; $(x,y).hover( function () { $(x).css({ backgroundColor: "#000", color: "#3ABCEF"}); $(y).show(); }, function () { $(x).css({ backgroundColor: "#333", color: "#FFF"}); $(y).hide(); } ); })(); } }); }); </code></pre> <h2>UPDATE ::: Here is the final working implimentation:</h2> <pre><code>var menu=new Array("#power","#services","#cashback","#schedule"); $(document).ready(function(){ for(var i in menu) { (function(x, y) { $(x+','+y).hover( function () { $(x).css({ backgroundColor: "#000", color: "#3ABCEF"}); $(y).show(); }, function () { $(x).css({ backgroundColor: "#333", color: "#FFF"}); $(y).hide(); } ); })(menu[i], (menu[i] + '_menu')); } }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload