treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] jQuery Problem - Probably me being an idiot!

  • Hi everyone

    I am just learning the syntax of jQuery and I was wondering if you could help me to see where I am going wrong.

    I know it can be done with CSS easily, it's just something I am trying out with jQuery instead to get used to it, I want the darkgreen colour to take effect when I hover over each anchor in the navigation and go back to its original colour when the mouse leaves the anchor. It seems to be activating ALL anchors, how do I single it out to just one at a time?

    Here is my pen - http://codepen.io/Watson90/pen/icAFl

    Thanks in advance...

  • $(document).ready(function() {
    
      $('nav li a').hover(function() {
    
        $(this).addClass('hover');
    
      }, function() {
    
        $(this).removeClass('hover');
    
      })
    
    });
    

    $(this) refers to the element or selection of elements that the selector has matched. ie in this case the a that is been hovered.

  • @ToxicFire YES! I remembered seeing something about 'this' but I couldn't figure out how to put it into the code, works perfect now. Thanks!

    Would you recommend anything else to help me learn jQuery? Or is it best to just play around with the code to explore the possibilities?

  • just keep the api open in a tab its got good examples.

  • @ToxicFire - thanks will do :)

  • What you could also do if you're going to reusing $(this) quite a lot in your scripts, or repeatedly using a selector is to "cache" them by turning them into a variable.

    For example, $this = $(this). Then you can just use $this in it's place.

    The benefit is that it avoids the need to repeatedly jump in and out of the dom and can help speed things up a tad.

  • Cheers for that @andy_unleash :)

    Really want to get more confident with jQuery, seems so difficult at the minute though...