28 February, 2012
0 Comments
1 category
You can add a CSS class to a HTML element, only when this class is not present on the HTML element, by using the jQuery function .toggleClass and using the switch parameter:
If your HTML page contains a div like:
<div id="title"> ... </div>
Adding the JavaScript code:
$(document).ready(function () { // The CSS class "titleStyling", will now be added, because it is does not exist on the title yet. $("#title").toggleClass("titleStyling", true); // Subsequent calls will not add extra classes, where the jQuery .addClass will. $("#title").toggleClass("titleStyling", true); // Subsequent calls will not add extra classes, where the jQuery .addClass will. $("#title").toggleClass("titleStyling", true); });
Will result in
<div id="title" class="titleStyling"> ... </div>
Tags: JavascriptjQuery
Category: Uncategorized