Reputation: 38332
Please run me through what happens on execution of this code. Basically looking at toggleClass(function(n)
$(document).ready(function(){
$("button").click(function(){
$("li").toggleClass(function(n){
return "listitem_" + n;
});
});
Upvotes: -1
Views: 122
Reputation: 5358
// when dom is loaded
$(document).ready(function(){
// when somebody clicks a button element
$("button").click(function(){
// add a specified class if it is present
// remove a specified class if it exists
$("li").toggleClass(function(n){
// the specified class name is variable
// based on the number of li elements (n)
// in the array of li elements
return "listitem_" + n;
});
});
Upvotes: 0
Reputation: 32052
It waits until all HTML elements are accessible from the DOM, which is necessary to reliably find the elements that are on the page. That usually means that the HTML code of the pages first must have loaded (but not necessarily the images). (Documentation for .ready
)
A function is bound to all button
elements that runs when the button is clicked. (Documentation for jQuery
and .click
)
For each li
element in the page, a function is called, which returns listitem_0
for the first one found, listitem_1
for the second, and so on. toggleClass
will remove that named class from the element if it already has it, but if it does not already have it, it will add it.
Hence, the button acts as a "toggle switch" that most likely switches the list items between two visually distinct appearances (defined by the page's CSS code).
Upvotes: 2
Reputation: 9491
when the element with the ID "button" is clicked The class listitem_[0-9] is added or removed from any li element depending on if it does or does not already have that class.
Upvotes: 0
Reputation: 163228
Well, the class that is returned from the function provided to toggleClass
will be added if it doesn't exist, and removed if it does exist.
The n
parameter is the index of the element in the node list, so the first element would have a class of "listitem_0"
and so on...
Upvotes: 1
Reputation: 27856
Check the comments
// when dom is loaded
$(document).ready(function(){
// on somebody clicks a button element
$("button").click(function(){
// change the class of li elements in the page
$("li").toggleClass(function(n){
// with a value depending on the number of li element in
// the array of li elements
return "listitem_" + n;
});
});
Upvotes: 2