jQuery mousedown()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery mousedown()

The mousedown() method adds an event handler function to an HTML element. This function is executed, when the left mouse button is pressed down, at the time while the mouse is over the HTML element.

This event is generally used together with mouseup() event.

Syntax:

  1. $(selector).mousedown()  

It triggers the mousedown event for selected elements.

  1. $(selector).mousedown(function)  

It adds a function to the mousedown event.

Parameters of jQuery mousedown() event

Parameter Description
Function It is an optional parameter. It executes itself when the mousedown event is triggered.

Example of jQuery mousedown() event

Let's take an example to demonstrate jQuery mousedown() event.

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>    
  5. <script>    
  6. $(document).ready(function(){    
  7.     $("#h1").mousedown(function(){    
  8.        $( "div" ).text( "mouse down event triggered" ).show().fadeOut( 2000 );   
  9.     });    
  10. });    
  11. </script>    
  12. </head>    
  13. <body>    
  14. <h1 id="h1">Enter this heading.</h1>   
  15. <div></div>   
  16. </body>    
  17. </html>    

Test it Now

Output:

Enter this heading.

jQuery mousedown() event example 2

Let's see another example of jQuery mousedown() event.

 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("p").mousedown(function(){  
  8.         $("p").css("background-color", "blue");  
  9.     });  
  10.     $("p").mouseup(function(){  
  11.         $("p").css("background-color", "lightyellow");  
  12.     });  
  13. });  
  14. </script>  
  15. </head>  
  16. <body>  
  17. <p>Press down the mouse left button over this p element</p>  
  18. </body>  
  19. </html>  
  20.     

Test it Now

Output:

Press down the mouse left button over this p element