Search code examples
jquery

Explain the jquery code, especially the toggleClass function


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;
        });
      });

Complete code is here


Solution

    1. 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)

    2. A function is bound to all button elements that runs when the button is clicked. (Documentation for jQuery and .click)

    3. 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).