4

Does anyone have any idea why my preventDefault code isn't working? return false returns fine, but it is my understanding that's not really the 'proper' way?

 if ($('.signup').length == 0) {
        $('.star').on('click',function(e){
            e.preventDefault();
            var starElement = $(this);
            var resourceId = starElement.parents('li').data('id');

            updateFavoritesSpan( starElement, starElement.hasClass('starred') );

            starElement.toggleClass('starred');
            starElement.parents('li').toggleClass('fvtd');
        });
        // voting
        $('.voting').on('click .up', function(e){
            e.preventDefault();
            sendVote($(this), 1);
        });

        $('.voting').on('click', '.down', function(e){
            e.preventDefault();
            sendVote($(this), -1);
        });
    }
Tallboy
  • 12,847
  • 13
  • 82
  • 173
  • Could you elaborate on "isn't working"? What sort of elements are those? And what does this have to do with ajax? – Pointy Jul 06 '12 at 19:55
  • With all browsers or just certain ones? – Mike Christensen Jul 06 '12 at 19:56
  • They're anchor links. when you click them it follows the link. these are ajax requests so they shouldnt follow the link – Tallboy Jul 06 '12 at 19:56
  • 1
    possible duplicate of [event.preventDefault() vs. return false](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Wayne Jul 06 '12 at 19:56

4 Answers4

7

return false; does both preventDefault and stopPropagation.

preventDefault stops the "default" action on the element, stopPropagation stops the event from bubbling up to the parent elements.

My guess is that there is an event on the parent that is still getting triggered when you only do preventDefault.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

The return false is not same as preventDefault().

In fact return false is combination of or is shorthand of:

  • preventDefault()
  • stopPropagation()

So try adding this as well (along with e.preventDefault()):

e.stopPropagation();
Blaster
  • 9,414
  • 1
  • 29
  • 25
2

there is a typo, change this:

$('.voting').on('click .up', function(e){

to:

$('.voting').on('click', '.up', function(e){
Ram
  • 143,282
  • 16
  • 168
  • 197
0

Just for completeness:

return false
also triggers
stopImmediatePropagation()
which cancels all the subsequent handlers on the same element (might come in handy when working with touchend event and meaning to cancel the subsequent click)

Read here the difference between stopPropagation() and event.stopImmediatePropagation():
jquery: stopPropagation vs stopImmediatePropagation
Community
  • 1
  • 1
emik
  • 903
  • 12
  • 11