8

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.

Throttlehead
  • 1,927
  • 6
  • 22
  • 36
  • http://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure , http://stackoverflow.com/questions/6978911/closure-inside-a-for-loop-callback-with-loop-variable-as-parameter , http://stackoverflow.com/questions/5555464/javascript-closure-of-loop –  Dec 10 '11 at 23:32
  • @pst - That is not the issue here. Did you read Rob's answer or run his fiddle? – Wayne Dec 10 '11 at 23:33
  • @pst - Clearly the OP intended the `$link` to be a local var. And clearly Rob answered correctly. – Wayne Dec 10 '11 at 23:36
  • @lwburk Just for you: http://stackoverflow.com/questions/1956698/why-does-a-global-variable-captured-in-a-get-callback-closure-always-hold-th –  Dec 10 '11 at 23:42

3 Answers3

12

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Doh! Thanks so much. My minds been blanking all day lol. Also probably has something to do with all the PHP I've been doing lately. Damn varying variable scopes! – Throttlehead Dec 10 '11 at 23:23
4

why not

$('.navItem > a').hover(
    function() {
        $(this).css('width', '224px');
    },
    function() {
        $(this).css('width', '192px');
    }
);

?

http://jsfiddle.net/Sth3Z/2/

Roman
  • 5,888
  • 26
  • 47
3

There is a better way of writing what u are trying to do:

$(".navItem a").hover(
    function() {
        $(this).css('width', '224px');
    },
    function() {
        $(this).css('width', '192px');
    }
);
Jonathan
  • 8,676
  • 20
  • 71
  • 101