简体   繁体   中英

event.preventDefault doesn't work in Firefox

I'm not sure why, but for some reason an event.preventDefault() call isn't working in Firefox. I'm using it to block clicking on an a link re-directing you to the href and instead run a click function. Markup as follows:

jQuery:

$('.sub-list-click a').click(function() {
    event.preventDefault();

    var sub = $(this).parent("li").next(".sub, .homepage-sub");

    if (sub.css('display') == 'none') {

        $(".sub, .homepage-sub").slideUp();
        $(".sub, .homepage-sub").children("li").animate({
            opacity: "0"
        }, 10);               

        setTimeout(function() { 
            sub.slideDown();                  
        }, 200);
        setTimeout(function() {
            sub.children("li").animate({
                opacity: "1"
            }, 200); 
        }, 500);   

    } else {
        sub.slideUp();
    }      

    return false;
});

It works in every other browser I've tested, just Firefox seems to be having some issues.

You need to add event as a parameter in your click function handler like this:

$(document).ready(function () {
    $('.sub-list-click a').click(function (event) {
        event.preventDefault();
        var sub = $(this).parent("li").next(".sub, .homepage-sub");

        if (sub.css('display') == 'none') {
            $(".sub, .homepage-sub").slideUp();
            $(".sub, .homepage-sub").children("li").animate({
                opacity: "0"
            }, 10);

            setTimeout(function () {
                sub.slideDown();
            }, 200);
            setTimeout(function () {
                sub.children("li").animate({
                    opacity: "1"
                }, 200);
            }, 500);

        } else {
            sub.slideUp();
        }
    });
});

Also note that this example is wrapped inside a document.ready event (you might already do this, but since it was not apparent i'll add this as note)

"Working" example here (that prevents the following to the link, not any of the animation stuff):
http://fiddle.jshell.net/79uuqmho/1/

Edit/Update:
The reason why it does not work in Firefox is because using event.something gives you an event not defined error which stops the execution of your script. Chrome on the other hand does not give that exception (probably due to event being defined somewhere in the window object) and allows the script to execute down to return false; (which is the same as {event.preventDefault(); /* AND */ event.stopPropagation();}

use any object in your event method parameters ie:

$('.sub-list-click a').click(function(e) {
    e.preventDefault();
    // other code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM