3

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?

Fil
  • 8,225
  • 14
  • 59
  • 85

3 Answers3

3
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');
    };
}
Script Host
  • 911
  • 1
  • 11
  • 22
2

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++) {
Dario
  • 6,152
  • 9
  • 39
  • 50
  • Check this to know the differenve between `let` and `var`: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav – Dario Apr 28 '18 at 16:31
0
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