Saturday 27 August 2016

Event Prevent Default in Javascript


Event PreventDefault

Event PreventDefault () Prevents the Default Browser Action In Response the Event Triggered . The preventDefault method prevents an event from carrying out its default functionality

Example : If we want to Stop Form Submit on click of Submit Button in form we can use PreventDefault to stop the default form submit behaviour of submit button in form .

As its name tells it just prevent occurence of the default behavior of event like if you need to prevent the click to occur on click event or stop entering of symbols in textbox if its character then make a check it entered character is symbol on keypress press and execute preventdefault ( ) to prevent default behavior of execution of  event on keypress and nothing will enter in textbox if its symbol .

CODE EXAMPLE


<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.preventDefault();
event.stopPropagation();
$('a').text('Click event prevented');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>

CODE EXPLANTION

If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to google.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.


Share this

0 Comment to "Event Prevent Default in Javascript "

Post a Comment