How to trigger click event on element only once while scrolling?

时间:2019-01-15 18:26:02

标签: javascript scroll triggers click

While listening to scrolling I want to trigger click event on an element only once. This event should scroll to an element. My code sofar:

window.addEventListener('scroll', () => {
  window.onscroll = slideMenu;
  if (window.scrollY > elementTarget.offsetTop) {
    const scrolledPx = (window.scrollY - elementTarget.offsetTop);

    if (scrolledPx > 100) {
      const link = document.getElementById('2');          
      link.click();
      link.removeEventListener('click'); // ????
    }
  }
}  

The problem is that while I meet the condition scrolledPx > 100 - it keeps triggerring the link.click() event. Any ideas how to do it?

4 个答案:

答案 0 :(得分:1)

定义变量并进行连续检查

<

答案 1 :(得分:1)

使用辅助布尔值:

let clicked = false;    
window.addEventListener('scroll', () => {
      window.onscroll = slideMenu;
      if (window.scrollY > elementTarget.offsetTop) {
        const scrolledPx = (window.scrollY - elementTarget.offsetTop);

        if (scrolledPx > 100) {
          if(!clicked) {
             const link = document.getElementById('2');
             link.click();
             clicked = true;
             link.removeEventListener('click'); // ????
          }          

        }
      }
    } 

答案 2 :(得分:1)

您需要检查以前是否单击了链接,或者删除滚动事件侦听器。我认为后一种方法是更好的解决方案,因为滚动事件侦听器经常触发,如果只需要一次,则可能没有额外的开销。


// Method 1
var didClick = false;
window.addEventListener('scroll', () => {
  window.onscroll = slideMenu;
  if (window.scrollY > elementTarget.offsetTop) {
    const scrolledPx = (window.scrollY - elementTarget.offsetTop);

    if (scrolledPx > 100 && didClick === false) {
      const link = document.getElementById('2');          
      link.click();
      didClick = true;
    }
  }
}  

// Method 2

function myScrollHandler(){
 window.onscroll = slideMenu; // You may want to move this elsewhere
  if (window.scrollY > elementTarget.offsetTop) {
    const scrolledPx = (window.scrollY - elementTarget.offsetTop);

    if (scrolledPx > 100 && didClick === false) {
      const link = document.getElementById('2');          
      link.click();
      window.removeEventListener('scroll', myScrollHandler); // ????
   }
  }
}

window.addEventListener('scroll', myScrollHandler);

答案 3 :(得分:1)

您可以考虑向元素添加新的布尔属性,而不是使用全局变量:

if (scrolledPx > 10) {
    const link = document.getElementById('2');
    // stopclik  is undefined at beginning
    if (link.stopclik == undefined) {
        link.click();
        link.stopclik = true;
        // set it to true.....
    }
}