w3resource

jQuery: Demonstrate how to handle click and double-click on a paragraph

jQuery Fundamental - I : Exercise-39

Demonstrate how to handle click and double-click on a paragraph.

Note: As the coordinates are window relative, so in this case relative to the demo iframe.

<body>
<p>Click or double click here.</p>
  <p id="result"></p>
</body>

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Demonstrate how to handle click and double-click on a paragraph.</title>
</head>
<body>
<p>Click or double click here.</p>
 <p id="result"></p>
 </body>
</html>

JavaScript Code :

$("p").bind( "click", function( event ) {
  var str = "( " + event.pageX + ", " + event.pageY + " )";
  $( "#result" ).text( "Click happened! " + str );
});
$( "p" ).bind( "dblclick", function() {
  $( "#result" ).text( "Double-click happened");
});
$( "#result" ).bind( "mouseenter mouseleave", function( event ) {
  $( this ).toggleClass( "over" );
});

Used Methods :

  • .toggleClass() : Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.
  • .bind() : Attach a handler to an event for the elements.

See the Pen jquery-fundamental-exercise-39 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Inserts a jQuery object before all paragraphs.
Next: Display a message when the focus is removed from an element.

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.