jQuery Preventdefault Function Example

Let's have a closer look at the jQuery .preventdefault() function.

Demo Code Download

Description

The .preventDefault() function can be applied to stop any element with a default action from firing: hyperlinks, keyboard shortcuts, form submit buttons etc. This example is probably the most common use and it stops a hyperlink from going to its destination (href). It's very useful for stopping those default actions and running your custom JavaScript actions instead. Lets have a look at an example of the preventdefault jQuery function in action. Further Reading »

Demo

jQuery Function Demo - jQuery4u.com

Demo: Preventing a hyperlink from going to href.

Run Demo View Code


Download

The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .preventdefault() function demo so you can try it yourself and change as you please.

The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!

Code

<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<html>
<title>jQuery Function Demo - jQuery4u.com</title>
<head>
    <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
    <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>

    <script type="text/javascript">

    var JQFUNCS =
    {
        runFunc:
        {
            /* ------------------------------ preventDefault Demo ------------------------------ */
            "preventdefault":
            {
                run: function(id)
                {
                    $('#'+id).html('<a href="http://www.jquery4u.com">http://www.jquery4u.com</a>');
                    $('#'+id+' a').live('click', function(e) {
                        e.preventDefault();
                        $('#'+id).html('Prevented going to http://www.jquery4u.com and displayed this message instead.');
                    });
                },

                reset: function(id)
                {
                    $('#'+id).empty().hide();
                }
            }
        }
    }

    </script>

</head>
<body>

<p class="example">Demo: Preventing a hyperlink from going to href.</p>
<p><a href="#" id="preventdefault-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="preventdefault-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="preventdefault-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="preventdefault"></div>

</body>
</html>
<!-- Copyright 2011 jQuery4u.com -->