Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
jQuery 2.0 Development Cookbook

You're reading from   jQuery 2.0 Development Cookbook As a web developer, you can benefit greatly from this book - whatever your skill level. Learn how to build dynamic modern websites using jQuery. Packed with recipes, it will quickly take you from beginner to expert.

Arrow left icon
Product type Paperback
Published in Feb 2014
Publisher Packt
ISBN-13 9781783280896
Length 410 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Leon Revill Leon Revill
Author Profile Icon Leon Revill
Leon Revill
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Document Object Model Manipulation FREE CHAPTER 2. Interacting with the User by Making Use of jQuery Events 3. Loading and Manipulating Dynamic Content with AJAX and JSON 4. Adding Attractive Visuals with jQuery Effects 5. Form Handling 6. User Interface 7. User Interface Animation 8. Understanding Plugin Development 9. jQuery UI 10. Working with jQuery Mobile Index

Adding and removing CSS classes to dynamically change their style

jQuery comes bundled with class manipulation functions in order to allow developers to easily alter the style of any HTML element.

Getting ready

For element style changes to be of any use, we first need to declare some styles within an HTML document. The following HTML code has a range of styles and elements that we can work with to illustrate this functionality of jQuery:

<!DOCTYPE html>
<html>
<head>
   <title>Add and remove CSS classes to dynamically change their style</title>
   <script src="jquery.min.js"></script>
   <script></script>
   <style type="text/css">
      .green {
         background-color: #008000;
         color: #FFFFFF;
      }
      .red {
         background-color: #FF0000;
         color: #FFFFFF;
      }
      .yellow {
         background-color: #FFFF00;
         color: #000000;
      }
   </style>
</head>
<body>
   <p id="sometext">
      Here is some text that can have different styles applied to it dynamically</p>
   <button id="green-btn">Green</button>
   <button id="red-btn">Red</button>
   <button id="yellow-btn">Yellow</button>
</body>
</html>

Within this HTML code, we have three buttons with their own unique IDs. We also have a paragraph with an ID. There are three CSS classes defined: green, red, and yellow. With jQuery, we can listen for the click of either of these buttons and then dynamically apply one of these classes to the paragraph element.

If you save this HTML file and open it within a browser, you should have the following web page:

Getting ready

How to do it…

  1. Add the following JavaScript code within the script tags in the HTML page you have just created:
    $(function(){
       //Listen for a click event on the green button
    $('#green-btn').click(function(){
       //When the green button has been clicked
       //Remove all classes current on the #sometext paragraph
       $('#sometext').removeClass();
       //Add the .green class to the #sometext paragraph
       $('#sometext').addClass('green');
    });
       //Listen for a click on the red button
    $('#red-btn').click(function(){
       //When the red button has been clicked
       //Remove all classes from the #sometext paragraph
       $('#sometext').removeClass(); 
       //Add the .red class to the #sometext paragraph 
       $('#sometext').addClass('red');
       });
       //Listen for a click on the yellow button
       $('#yellow-btn').click(function(){
          //When the yellow button has been clicked
          //Remove all classes from the #sometext paragraph
       $('#sometext').removeClass();
       //Add the .yellow class to the #sometext paragraph 
       $('#sometext').addClass('yellow');
       });
    });
  2. Opening the HTML document in your browser will now allow you to change the #sometext paragraph style by selecting either of the three available buttons.

How it works…

jQuery allows us to attach a click event handler to any element by using the click() function. We can then execute a set of code of our choice by passing a function as an argument to the click() method. To add a class to an element, we can use the addClass() function and provide the class name as a string argument. This function will add the specified class name to the selected element.

jQuery also provides us with a removeClass() function. This allows us to either remove a specific class from an element by providing removeClass() with a string, or when a string is not provided, it will remove all the classes from the selected element. We will need to use this in order to prevent multiple classes being added to the paragraph element when either of the buttons has been clicked more than once.

The following screenshot illustrates this web page after the Yellow button has been clicked:

How it works…

See also

  • Modifying the DOM element properties
  • Enabling and disabling buttons by changing their properties
You have been reading a chapter from
jQuery 2.0 Development Cookbook
Published in: Feb 2014
Publisher: Packt
ISBN-13: 9781783280896
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image