Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each(): variable in callback always has last value?

Can't seem to figure out what's going on here.

<div id="navigation">
    <ul id="navList">
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX.html">Discover</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/documentation.html">Documentation</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/download.html">Download</a></li>
        <li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/donate.html">Donate</a></li>
    </ul>
    <script type="text/javascript">
        $('.navItem').each(function() {
            $link = $(this).children('a');
            $link.hover(
                function() {
                    $link.css('width', '224px');
                },
                function() {
                    $link.css('width', '192px');
                }
            )
        });            
    </script>
</div>

http://jsfiddle.net/Sth3Z/

It should be doing it for each link, instead it only changes the last link no matter which one is being hovered over.

like image 874
Throttlehead Avatar asked Dec 10 '11 23:12

Throttlehead


1 Answers

Add var before $link: http://jsfiddle.net/Sth3Z/1/

    $('.navItem').each(function() {
        var $link = $(this).children('a');   // `var` added

Currently, you're declaring a global variable, which will be overwritten at each iteration in the loop.

like image 111
Rob W Avatar answered Nov 15 '22 22:11

Rob W