Conditional click handlers

Why your click handlers are not working as you expect.

by Brenton Strine

HTML

<div id="buttons">
    <button>turn blue</button>
    <button class="red">only turn text red</button>
    <button>turn blue</button>
    <button>turn blue</button>
    <button>turn blue</button>
</div>

whoops, background turns blue too. we only wanted the text to turn red.

JavaScript

$(document).ready(function(){
    $("#buttons").on("click", "button", function(){
        $(this).css("background","blue");
    });
    $("#buttons").on("click", ".red", function(){
        $(this).css("color","red");
    });

});