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 :


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

CSS Code:

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


HTML Code :

<!DOCTYPE html>
<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>
<p>Double-click here to change the background color.</p>

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]

Live Demo:

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

Contribute your code and comments through Disqus.

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

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.