w3resource

jQuery: Double click on a paragraph to toggle background color

jQuery Events : Exercise-5 with Solution

Double click on paragraph to toggle background color.
Sample Data :

HTML :

<body>
 <p>Double-click here to change the background color.</p>
 </body>
 

CSS Code:

p {
background: blue;
color: white;
}
p.dbl {
background: yellow;
color: black;>
}

Solution:

HTML Code :


<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Double click on paragraph to toggle background color</title>
</head>
<body>
<p>Double-click here to change the background color.</p>
</body>
</html>

JavaScript Code :

var pdbl = $( "p:first" );
pdbl.dblclick(function() {
  pdbl.toggleClass( "dbl" );
});

Note : In jQuery stoggleClass( className ) method is used to add or remove one or more classes from each element in the set of matched elements. It has the following parameter.

  • className : One or more class names (separated by spaces) to be toggled for each element in the matched set. [Type: String]

Go to:


PREV : Hide all headings on a page when they are clicked.
NEXT : Click a header to add another.

Live Demo:

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


Contribute your code and comments through Disqus.

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.