javascripthtmljquery

What is the role of index in the callback function of click in JQuery?


The following code works. I want to understand why is i used there as index in the argument list of the callback function. What is its purpose? If I remove i from the argument list of the call back function, it doesn't work. Why?

$("#btn1").click(function(){
  $("#test1").text(function(i, origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")";
  });
});

Solution

  • To many of the jQuery methods, you can pass:

    1. undefined (nothing)
    2. a value (a string, a number, a boolean, an object...)
    3. a function statement (a callback).

    So focussing on the 3rd one. When you provide a function statement, consider that the method does a couple things before calling the passed-in function. That is why it is called a callback. So .text(callback) is calling (read executing) your callback by passing in some arguments.

    In this case, the first agument is a number representing the index of the matched element. So you can inagine a loop here. The second is the original text of the matched element.

    Documentation

    So you have to write the callback taking this in account. You are not forced to use the arguments, but it's there for you to use.

    so...

    $(selector).text(function(i, origText){
      
      // outputs a number
      console.log(i)
      
      // outputs a tring
      console.log(origText)
      
      // Expected to be returned is a string to use to set the element's text
      return "Something else"
    }
    

    In the above, since the argument where not used in order to build the returned string, it is the same as:

    $(selector).text("Something else")
    

    But using a function allows you to use the arguments of the callback in the text to be set:

    $(selector).text(function(i, origText){
      
      // outputs a string containing the index number in the $(selector) collection
      return "I am element " + i;
    }
    

    Or to apply some logic like:

    $(selector).text(function(i, origText){
      
      // Only the text of the second matching element will be changed (index is zero-based)
      if(i == 1){
        return "I am element " + i;
      }else{
        return origText
      }
    }
    

    Now, it is up to you to name the arguments... If that was the question.

    $(selector).text(function(pineapple, banana){
      
      // outputs a number
      console.log(pineapple)
      
      // outputs a tring
      console.log(banana)
      
      // Expected to be returned is a string to use to set the element's text
      return "Something else"
    }
    

    If you are only interested in the banana argument, you still have to name the first in order to name and use the second. Just do not use pineapple in the function body if it is useless to you.

    Hoping it is helpful. ;)