Grow your CSS skills. Land your dream job.

jQuery Problem – Probably me being an idiot!

  • # November 20, 2012 at 3:47 pm

    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…

    # November 20, 2012 at 3:57 pm

    $(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.

    # November 20, 2012 at 4:00 pm

    @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?

    # November 20, 2012 at 4:02 pm

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

    # November 20, 2012 at 4:03 pm

    @ToxicFire – thanks will do :)

    # November 20, 2012 at 4:40 pm

    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.

    # November 20, 2012 at 5:16 pm

    Cheers for that @andy_unleash :)

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

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".