Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




EVENTS - event.isDefaultPrevented()


The event.isDefaultPrevented() is used to check, if the preventDefault() method is invoked for the element.


Let us simplify with the below example.


Example :



<html>
  	<head>
    	<title> My First Programme </title>
        <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
  	</head>

  	<body>
    	<h1> JQuery </h1>
   	
        <a href = "https://www.google.com"> Click to go to google </a>

      	<script>
      
			$( "a" ).click(function( event ) {
  				event.preventDefault();
  				if (event.isDefaultPrevented()) {
  					alert("Prevent default is not allowing the default operation")
  				}	
            });
            
      	</script>      
  	</body>
</html>


Output :



So, if you see the above code. We can see that there is an <a> element,


<a href = "https://www.google.com"> Click to go to google </a>

And when we click on the above link, we are taken to https://www.google.com.


Now, if we see the JQuery statement,


$( "a" ).click(function( event ) {
	event.preventDefault();
	if (event.isDefaultPrevented()) {
		alert("Prevent default is not allowing the default operation")
	}
});

When we click on the <a> element, the JQuery statement gets triggered.


$( "a" ).click(...);

And the anonymous function inside the click() event,


function( event ) {
	event.preventDefault();
	if (event.isDefaultPrevented()) {
		alert("Prevent default is not allowing the default operation")
	}
}

We have used the event.preventDefault() that prevents any default actions from happening.


As in this case, the default action to click on the <a> element, to reach the site https://www.google.com.


<a href = "https://www.google.com"> Click to go to google </a>

And the event.preventDefault() stops the above action.


Finally, we check, if the default action is prevented or not using the if statement.


if (event.isDefaultPrevented()) {
	alert("Prevent default is not allowing the default operation")
}

And since the default action is prevented, we get the alert.


alert("Prevent default is not allowing the default operation")