Search code examples
javascriptjqueryeventstarget

jQuery I can't access to getAttribute attribute in e.currentTarget


I am using an arrow function with setTimeout and am having issues accessing the getAttribute of the clicked element.

What could be the cause of this issue?

let myTimeout;
const time = 2000;

$(document).on("touchstart", "figure img", (e) => {
  myTimeout = setTimeout(function(e) {
    var figure = e.currentTarget;
    var img = figure.querySelector("img");
    var src = img.getAttribute("src");
    console.log("src>" + src);
    console.log("PRESS DELAY");
  }, time);
});
<section>
  <figure>
    <img src="https://picsum.photos/536/354" />
  </figure>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


Solution

  • The issues are that

    1. your event listener is setting e to img already (since you did "figure img", so when you do figure = e.currentTarget; img = figure.querySelector('img') it's trying to find a child img of the img, which doesn't make sense.

    2. the function in setTimeout is shadowing the e variable, so e will be undefined inside of that function.

    It should look like this:

    let myTimeout;
    const time = 2000;
    
    $(document).on("touchstart", "figure img", (e) => {
      myTimeout = setTimeout(function() {
        var img = e.target;
        var src = img.getAttribute("src");
        console.log("src>" + src);
        console.log("PRESS DELAY");
      }, time);
    });
    <section>
      <figure>
        <img src="https://picsum.photos/536/354" />
      </figure>
    </section>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>