We’ve talked about the event model of javascript. Related to this topic is the usage of preventDefault(),stopPropagation , return false, returnValue=false, cancelBubble=true, which is very confusing.
Among these, preventDefault() is most commonly seen, which prevents the default behavior of the event on the target element from occurring. For example, the default behavior of the click event on an <a> element is to navigate to a url. The default behavior of the click event on a <input type=”submit”> button is to submit the form. You can call this function in any event handler in the bubbling process that catches the event. By default, the default behavior will be triggered after all event handlers are called. If any event handler calls preventDefault, the default behavior will not be triggered. Note that preventDefault() is a method of event so can only be used in an event handler such as:
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); e.preventDefault(); } </script>
You can also set window.event.returnValue=true to reach the same aim:
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); window.event.returnValue = true; } </script>
Although window.event seems a global variable, it only gets generated in an event handler thus can only be accessed in an event handler.
The third method to prevent the default behavior is letting any event handler in the bubbling phrase return a false value such as:
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); return false; } </script>
Stopping propagation is a totally different concept from stopping default behavior. Stopping propagation means the event cannot bubble to higher nodes any longer so handlers bound to higher nodes will not be called. There are two methods to stop an event from propagation:
- call the stopPropagation method of event in question such as:
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); e.stopPropagation(); } </script>
Since stopPropagation is a method of event, it can only be called in an event handler.
- Set window.event.cancelBubble=true
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); window.event.cancelBubble=true; } </script>
Note that although stopPropagation /cancelBubble can stop event from propagating to higher level, they cannot prevent default behavior from happening.
To prevent events from propagating meanwhile disabling the default behavior, you should combine stopPropagation with preventDefault:
<script> var a = document.getElementById("a"); a.onclick =function(e){ alert("hello"); window.event.cancelBubble=true; e.preventDefault(); } </script>