Hi all, I am slightly confused about passing functions to the addClass method. This code is taken from the jquery.com site http://api.jquery.com/addClass/:

<!DOCTYPE html>
<html>
<head>
  <style>
  div { background: white; }
  .red { background: red; }
  .red.green { background: green; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" and "red" classes.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>

<script>
  $("div").addClass(function(index, currentClass) {
    var addedClass;

    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");
    }

    return addedClass;
  });
</script>

</body>
</html>

Couple of points:
1)how is the script called? There is no call, does it run on document load?
2)addClass(function(index, currentClass) {: what are these 2 parameters index and currentClass, where do they come from?
3)return addedClass; if they add this, does it mean that the whole expression gets the value of addedClass?

thanks

  1. The script is called as soon as the browser interpreter gets to line 20.

  2. index is the position of the current div, currentClass get the value of that div's class attribute (zero, or more space separated classes).

  3. What is returned is added to the current class(es) of that div.

crystal clear, thanks for the explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.