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]
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/jquery-exercises/jquery-events-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics