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




EVENTS - trigger()


The trigger() Event is used to trigger the default behaviour of an event. Also it can trigger any event specified.


At first let us look, how the trigger() Event can be used to trigger the default behaviour of an event.


Example :



<html>
  	<head>
    	<title> My First Programme </title>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	<form action = "submit">
    	
    		Type Something and click on the submit button : <input type = "text">  <br/><br/>	
        	<input type = "submit"> 
        	
        </form>	
        
        

      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
			$('form').trigger( "submit");
            
      	</script>      
  	</body>
</html>  


Output :



So, if you see the above output, you are not even allowed to type something. Before you even knew, the form got submitted.


This is because of the trigger() event in JQuery statement,


$('form').trigger( "submit");

Just remember, in this case the default action of the <form> element,


<form action = "submit">
	Type Something and click on the submit button : <input type = "text">  <br/><br/>
	<input type = "submit">
</form>

Is submit.


And since the trigger() event is used to execute the default action of an element,

java_Collections

The submit event gets triggered before we could type anything.


Now, in the next example, let us see, how can we trigger the focus event on a button click.


Example :



<html>
  	<head>
    	<title> My First Programme </title>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	Click on the below button to get focus : <input type = "text">  <br/><br/>	
        <button> Click Here </button>    

      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      	
      		$('button').click( function() {
				$('input').trigger("focus");
			});	
            
      	</script>      
  	</body>
</html>  


Output :



So, if you look at the above code, there is an <input> element of type text.


<input type = "text">

And a <button>,


<button> Click Here </button>

Now, all we want is, on button click, we want the <input> element to get focussed.


And that happens with the below JQuery statement.


$('button').click( function() {
	$('input').trigger("focus");
});

So, on button click, the click() event gets triggered,


$('button').click(...);

And the anonymous function gets executed,


function() {
	$('input').trigger("focus");
}

Where the trigger() event locates the <input> element and executes the focus event for the <input> element. And the <input> element to get focussed.