Mona Coder
Mona Coder

Reputation: 6316

How can I bind Dom $(this) From Another Function

Can you please take a look at this code and let me how can I bind $(this) in an external function inside dom event?

$(".adder").on("click", function(){
    updateText();
});

function updateText(){
   $(this).next(".mapper").html("Got You!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container">
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-default adder">Left</button>
  <button type="button" class="btn btn-default mapper">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-default adder">Left</button>
  <button type="button" class="btn btn-default mapper">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div>  

</div>

Upvotes: 0

Views: 24

Answers (3)

Inus Saha
Inus Saha

Reputation: 1918

one way to do this is following:

function updateText(){
   $(this).next(".mapper").html("Got You!");
}

$(".adder").on("click", updateText);

another is

function updateText(){
   $(this).next(".mapper").html("Got You!");
}

$(".adder").on("click", function(){
    updateText.bind(this)();
});

Upvotes: 2

jvk
jvk

Reputation: 2201

function updateText(e){
   e.next(".mapper").html("Got You!");
}

        $(".adder").on("click", function(){
               updateText($(this));
        });

Upvotes: 0

greendemiurge
greendemiurge

Reputation: 509

You should be able to pass this along as an argument:

$(".adder").on("click", function(){
    var node = $(this);
    updateText(node);
});

function updateText(node){
   node.next(".mapper").html("Got You!");
}

Upvotes: 3

Related Questions