Search code examples
jqueryjquery-on

JQuery - change text of button, while toggle another object, using on()


The HTML is a list of buttons, that toggles an element on an off.

I want to change the text on the button, from "show" to "hide". i want it to be done from withing the complete() callback. how can i access the element that was clicked?

I have this JS-code:

  $("body").on("click", ".selector", function(eve) {
     $(".selector", $(this).parent()).toggle(function(){
        $(/*here comes the element that was clicked*/).text(
            function(i,text){
                return text == "show" ? "hide" : "show"; 
            }
        );
     });
  });

Solution

  • Store a reference to this

    $("body").on("click", ".selector", function(eve) {
     var that = $(this);
     $(".selector", $(this).parent()).toggle(function(){
        that.text(
            function(i,text){
                return text == "show" ? "hide" : "show"; 
            }
        );
     });
    });