views:

46

answers:

1

Hi,

Is it possible to stop the automatic preventDefault() from applying in a simple Jquery toggle function?

$(".mydiv").toggle(
    function () {
        $(this).addClass("blue");
    },
    function () {
        $(this).removeClass("blue");
    }
);

The above prevents elements inside the div from responding normally to the click.

It doesn't have to be the toggle() function - anything that allows toggling a class on and off AND doesn't return false would be great.

Thanks.

+1  A: 

The documentation admits this as a limitation:

Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

source: http://api.jquery.com/toggle/

Which is to say, there's no built-in way. Happily, as the documentation also says, it's "relatively straightforward to implement the same behavior by hand". In this instance:

$(".mydiv").click(function(){
  $(this).toggleClass("blue");
}}

(Read more about toggleClass().)

D_N
Fantastic thanks, that's what I was looking for.
Tom