Skip to content Skip to sidebar Skip to footer

How And When To Use Preventdefault()?

From this tutorial, it is said: preventDefault(); does one thing: It stops the browsers default behaviour. I searched online for the examples of preventDefault(), I can only se

Solution 1:

1.in what else situation we can use preventDefault()?

Actually any type of event, you can stop its default behavior with the preventDefault(); So not only submit buttons, but keypresses, scrolling events, you name it and you can prevent it from happening. Or if you'd like add your own logic to the default behavior, think of logging an event or anything of your choice.

2.how could I find out all the browsers default behaviour? e.g. if I click a button, what is the browsers default behaviour?

What do you mean with this? Mostly the default behavior is kind of implied. When you click a button, the onclick event fires. When you click the submit button, the form is submitted. When the windows scrolls, the onscroll event fires.

Solution 2:

1) In what else situation we can use preventDefault()?

Various form fields update their state in response to certain events, such as a checkbox when you click it. If you preventDefault on click, the checkbox reverts to its earlier checked state. There are lots of behaviors — when keys are pressed, when the window is scrolled, when an element is focussed...

2) How could I find out all the browsers default behaviour? e.g. if I click a button, what is the browsers default behaviour?

The specification lists the "activation behavior" of each element. Compare the activation behavior described for a elements to that described for input[type=checkbox], for instance. (The "pre-click activation steps" are interesting, too.)

Solution 3:

Every item in the DOM has some 'default behaviour'. This is for every browser about the same (some exceptions excluded). If you want your own logic to be executed instead of the default behavior, you can use the preventDefault() function. The same goes for the stopPropagation() function which stopt events from bubbling up the event tree if you just want your own logic being executed and nothing else from there on.

Solution 4:

You can use it in every type of event, for example:

element.onclick = function(event) {
    event = event || window.eventif (event.preventDefault) { // W3C variantevent.preventDefault()
    } else { // IE < 9 variant. It doesn't work in older version of IEevent.returnValue = false
    }
}

What's the difference between returning false or using event.preventDefault?

  1. return false. Stops the default browser action AND finish the handling.
  2. event.preventDefault. Stops the default browser action BUT doesn't finish the handling

This is a useful link that explains it deeply.

Post a Comment for "How And When To Use Preventdefault()?"