BrunoLM
BrunoLM

Reputation: 100331

How to prevent events from raising?

Is it possible that if one event raise prevent others from raising?

Example on jsFiddle

$(window).click(
    function(e)
    {
        $("#out").html("preventing next event from happening\n");
    });

$(window).click(
    function(e)
    {
        $("#out").html($("#out").html() + "evil event should not write here");
    });

Upvotes: 2

Views: 435

Answers (2)

gailbear
gailbear

Reputation: 519

$(window).click(
    function(e)
    {
        $("#out").html("preventing next event from happening\n");
        e.stopImmediatePropagation();
    });

$(window).click(
    function(e)
    {
        $("#out").html($("#out").html() + "evil event should not write here");
    });

http://api.jquery.com/event.stopImmediatePropagation/ -- read more here

Upvotes: 4

JasCav
JasCav

Reputation: 34632

Well, you can use preventDefault() to stop the other event from occurring. This may be overkill for your solution, however, because it doesn't really give you a choice in which event fires.

http://jsfiddle.net/c52Wr/1/

$(window).click(
    function(e)
    {
        $("#out").html("preventing next event from happening\n");
        e.preventdefault();
    });

$(window).click(
    function(e)
    {
        $("#out").html($("#out").html() + "evil event should not write here");
    });

A better solution may be to accept a click and some parameter and check that parameter to decide how you want to respond.

Upvotes: 3

Related Questions