0

So basically I have a few links, when you click one, it should add the highlighted class. I also have a button that when clicked should hide the link with the highlighted class.

This seems trivial and should be very simple, but I can't understand why my code does not work. Another thing, is for some reason, the links still go through once clicked in the fiddle. Not sure if it's something with jsfiddle and how it handles external links?

Here is my fiddle: http://jsfiddle.net/ZPGe7/1/

Maverick
  • 1,123
  • 5
  • 16
  • 30

1 Answers1

1

You should not cache the jQuery object, because it doesn't update when the elements receive different class names. Also, use event.preventDefault() to prevent the link from being followed. Directly use $('.links a.highlight') in your code.

Fiddle: http://jsfiddle.net/ZPGe7/2/

$(function() {
    $('.links a').live('click',function(ev){
            $('.links a.highlight').removeClass('highlight');
            $(this).addClass('highlight');
            ev.preventDefault(); //Prevent link from being followed
    });
    $('#submit').live('click',function(){
        $('.links a.highlight').hide();
    });
});        
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks Rob works great! So return false vs prevent default, the difference is just that prevent default does what return false does plus it does not cache the class? – Maverick Oct 20 '11 at 17:42
  • hmmm... why can't we use a declared variable like in the original fiddle? – Maverick Oct 20 '11 at 17:49
  • @Maverick In your code, you were caching the `$('.links a.highlight')` selector. This caused the `click` event (bound to `#submit`) to not behave as expected: The "old" list of `a.highlight` elements was empty, and doesn't update when the class names of elements change. – Rob W Oct 20 '11 at 17:51