Cancel event

In this chapter you will learn:

  1. How to use event.preventDefault() to cancel jQuery event
  2. How to use event.stopPropagation()
  3. How to return false to cancel event

event.preventDefault()

The following code cancel the default action by using the preventDefault method.

<html><!--from   j av  a  2  s  .  co m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
              $("adiv").live("click", function(event){
                   event.preventDefault();
               });
        });
    </script>
  </head>
  <body>
    <body>
       <div><h1>header 1</h1></div>
    </body>
</html>

Click to view the demo

event.stopPropagation()

To Stop only an event from bubbling by using the stopPropagation method.

$("form").bind("submit", function(event){
  event.stopPropagation();
});

Return false to cancel event

The following code returns false to Cancel a default action and prevent it from bubbling up.

<html><!--   j  a v a  2s.c om-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
              $("div").live("click", function() { return false; })
        });
    </script>
  </head>
  <body>
    <body>
       <div><h1>header 1</h1></div>
    </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Information about event target
Home » jQuery » Event
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.on()
.one()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()