jQuery Preventdefault Function Example

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

Demo Code Download


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 »


jQuery Function Demo - jQuery4u.com

Demo: Preventing a hyperlink from going to href.

Run Demo View Code


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!


<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<title>jQuery Function Demo - jQuery4u.com</title>
    <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 =
            /* ------------------------------ preventDefault Demo ------------------------------ */
                run: function(id)
                    $('#'+id).html('<a href="http://www.jquery4u.com">http://www.jquery4u.com</a>');
                    $('#'+id+' a').live('click', function(e) {
                        $('#'+id).html('Prevented going to http://www.jquery4u.com and displayed this message instead.');

                reset: function(id)



<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>

<!-- Copyright 2011 jQuery4u.com -->