toggleClass() example

basic jQuery

by Mindy McAdams

HTML

<h1>Example</h1>

<p>My page has a section with the ID "episodes," and inside that section I have a lot of DIVs. Each DIV has the class "episode." What does the following code do if I click one of those DIVs?</p>

<section id="episodes">
    
    <div class="episode">
        <p>"The City on the Edge of Forever"</p>
    </div>
    <div class="episode highlighted">
        <p>"Space Seed"</p>
    </div>
    <div class="episode">
        <p>"Mirror, Mirror"</p>
    </div>
    <div class="episode">
        <p>"The Doomsday Machine"</p>
    </div>
    <div class="episode">
        <p>"Amok Time"</p>
    </div>
    
</section>

CSS

.highlighted {
    background-color: #ff0;
}

JavaScript

// toggleClass() example 

$(document).ready(function(){ 
    
	$('#episodes').on('click', '.episode', function() {
    	$(this).toggleClass('highlighted');
    });

});