Search code examples
jquerydom-traversal

Act on Clicked Element in Callback Function


I'm writing some JS functions to handle an element click and process the JSON response. The issue I'm having is referencing the clicked element outside of the click function.

HTML mockup:

<div class="container">
  <div class="link">
    <a href="#" onclick="linkify()">Test</a>
  </div>
  <div class="output">
    <textarea class="output-textarea"></textarea>
  </div>
</div>
<div class="container">
  <div class="link">
    <a href="#" onclick="linkify()">Test</a>
  </div>
  <div class="output">
    <textarea class="output-textarea"></textarea>
  </div>
</div>

And the JS:

// link function
function linkify() {
    // save reference to click element
    activeElement = $(this);
    // make AJAX call
}

// callback function; the parameters of this function 
// are defined by an API and cannot be changed
function callback(json) {
    $(activeElement).closest('.container').find('.output-textarea').val(json);
}

jsFiddle here: http://jsfiddle.net/Lqaw05j8/4/

In my fiddle, the event fires with all variables defined, but my jQuery DOM traversal doesn't work.


Solution

  • You need to pass this as an argument to the function:

    <a href="#" onclick="linkify(this)">Test</a>
    
    function linkify(element) {
        // save reference to click element
        activeElement = element;
        // make AJAX call
    }
    

    Note that using a global variable like this is not the best way to pass the context to the callback. If the user clicks on another element before the callback fires, it will change the active element. Consider using the context: option to $.ajax() to pass the context, or make the callback function a closure.