简体   繁体   中英

preventDefault stops function from working

I have this jquery:

jQuery('#overlayBtn').click(function(e){
    e.preventDefault();
    jQuery('#overlay').css('display','flex');
});

If I remove the preventDefault() it works fine but the page jump up to the top as I have a # as the href. I want to stop the default click behavior but make my overlay show.

How do I do this?

Just add at the end of function return false;

jQuery('#overlayBtn').click(function(e) {
    jQuery('#overlay').css('display','flex');
    return false;
});

As another user said before, return false; could be the soulution for this case but consider this is not a good practice.

Please refer to the following link to see why you shold't use that line of code: https://web.archive.org/web/20160603125641/http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

In addition, you can use the attribute href="javascript:void(0)" to achieve the same result.

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