w3resource

jQuery : Attach a click and double-click event to a element

jQuery Events : Exercise-1 with Solution

Attach a click and double-click event to the <p> element
Sample Data :

HTML :

 <body>
 <p>Click me!</p>
 </body> 
For single click append the following paragraph :

This is a click Event

For double-click append the following paragraph :

This is a double-click Event

Solution :

HTML Code :

<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Attach a click and double-click event to the <p> element</title>
</head>
<body>
<p>Click me!</p>
<div id="result"></div>
</body>

JavaScript Code :

$("p").bind("click", function(){
   $( "<p>This is a click Event</p>").appendTo( "#result" );
   });
   $("p").bind("dblclick", function(){
     $( "<p>This is a double-click Event</p>"  ).appendTo( "#result" );
	 });

Note: In jQuery click(handler) method is used to bind an event handler to the "click" JavaScript event, or trigger that event on an element. It has the following parameter :

  • handler : A function to execute each time the event is triggered. [Type: Function( Event eventObject )]

dblclick( [eventData ], handler ) method is used to bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. It has the following parameter :

  • eventData : An object containing data that will be passed to the event handler. [Type: Function( Event eventObject )]
  • handler : A function to execute each time the event is triggered. [Type: Function( Event eventObject )]

Live Demo:

See the Pen jquery-events-exercise-1 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: jQuery Events Exercises
Next: Append a <p> element with a text message when an <input> field is changed.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.