jQuery CSS - Toggle a specified class when an element is clicked
jQuery CSS: Exercise-10 with Solution
Toggle a specified class when an element is clicked.
Sample Data :
HTML :
<body> <p></p> </body>
CSS:
<style> p { margin-top:20px; margin-left: 10px; padding: 5px; border: 2px solid #666; } </style>
Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Toggle a specified class when an element is clicked</title>
</head>
<body>
<p>Click on the Paragraphs</p>
<p>jQuery Exercises</p>
<p>JavaScript Exercises</p>
</body>
</html>
CSS Code:
p {
margin: 5px;
font-size: 15px;
cursor: pointer;
}
.highlight {
background: #F4FA58;
}
JavaScript Code:
$( "p" ).click(function() {
$( this ).toggleClass("highlight");
});
Live Demo:
See the Pen jquery-css-exercise-10 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Find the offset of an element.
Next: jQuery Events Exercises
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-css-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics