w3resource

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");
});

Go to:


PREV : Find the offset of an element.
NEXT : jQuery Events Exercises

Live Demo:

See the Pen jquery-css-exercise-10 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.