Fil
Fil

Reputation: 8873

I got undefined dataset, when getting data attribute in html

I have this code in html,

<ul id="locationSelect" style="visibility: visible;">
  <li class="location-select" data-num="9"></li>
  <li class="location-select" data-num="9"></li>
  <li class="location-select" data-num="7"></li>
  <li class="location-select" data-num="6"></li>
</ul>

Now I want to get the value of data-num attribute when the user click on any <li> element using pure javascript.

Here the code for javascript so far.

let locSel = document.getElementById('locationSelect').getElementsByClassName('location-select');

for(var i=0; i < locSel.length; i++) {
    locSel[i].onclick = function() {
      let markerNum = locSel[i].dataset.num;
      google.maps.event.trigger(markers[markerNum], 'click');
    };
}

Given that code, I got undefined, on the part of locSel[i] and then got stack (I dont know the right spelling for this word stack). I have know idea.

any suggestion please?

Upvotes: 3

Views: 9854

Answers (3)

Shampy Dev
Shampy Dev

Reputation: 1

const imgRef = document.querySelectorAll("img[data-src]");

const observer = (entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) return;
    entry.target.src = imgRef.dataset.src;
  });
  console.log(entries);
};

const imgObserver = new IntersectionObserver(observer, {
  root: null,
  threshold: 0,
});
imgRef.forEach((image) => {
  imgObserver.observe(image);
});

In My Case i am trying to lazy load images using data-src But It is not defined i dont know if i have defined imgRef correctly or not

Upvotes: 0

Dario
Dario

Reputation: 6280

When your onclick handler is called, i is equal to 4, so locSel[i] will always be undefined. This is because you declared i as a var and the same variable will live and be accessed through all your code.

In order to have i get a new binding for every iteration of the loop, use let instead of var:

for(let i=0; i < locSel.length; i++) {

Upvotes: 2

Script Host
Script Host

Reputation: 921

let locSel = document.getElementById('locationSelect').getElementsByClassName('location-select');

for(let i=0; i < locSel.length; i++) {
    locSel[i].onclick = function() {
      let markerNum = locSel[i].dataset.num;
      google.maps.event.trigger(markers[markerNum], 'click');
    };
}

Upvotes: 3

Related Questions