1

I have this function:

$(document).ready(function() {

    $('.UIDropDown').click(function () {

        $('.button', this).click(function(e){ e.preventDefault()});

        $(this).addClass('active');


    });

});

And the following html:

<div class="UIDropDown">

    <a href="" class="button">button link</a>

    <ul class="submenu">
        <li><a href="">Item</a></li>
        <li><a href="">Item</a></li>
        <li><a href="">Item</a></li>
    </ul>

</div>

Why is the e.preventDefault() not working on the .button? The page still refreshes .

Thx,

kevinius
  • 4,232
  • 7
  • 48
  • 79

5 Answers5

4

Because you bind the event handler after the event has actually ocurred, and it doesn't get executed. Bind the event handler to the element in the DOM ready event handler:

$(document).ready(function() {
    // Bind event handler to the button
    $('.UIDropDown .button').click(function(e) { 
        e.preventDefault(); 
    });
    // Bind event handler to the div (click on .button will trigger both)
    $('.UIDropDown').click(function () {
        $(this).addClass('active');
    });
});​

Here's a working example.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

try "return false;" instead of preventDefault(); That will block to going to URI. As in:

$('.button', this).click(function(e){ return false; });
Arda
  • 6,756
  • 3
  • 47
  • 67
0

You don't need that link click function inside the div click function.

try this?

$('.UIDropDown').click(function() {
    $(this).addClass('active');
});

$('.button').click(function(e) {
    e.preventDefault()
});​

chris
  • 605
  • 1
  • 9
  • 27
0

try this.

  $('.UIDropDown').click(function () {

    $('.button', this).click(function(e){ return false; });

    $(this).addClass('active');


  });
  • 1
    That won't make any difference. `preventDefault` will work fine if the event binding happens in the right place. See my answer. – James Allardice Nov 22 '12 at 10:40
0

you should write

 $('.button').click(function(e){ e.preventDefault()});

outside the click handler of the $('.UIDropDown')

Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
  • 1
    You probably don't want the `this` context argument when you move the `.button` event binding outside of the other event handler. – James Allardice Nov 22 '12 at 10:41