简体   繁体   中英

Event Listener Scroll or Click

I have a web page with several sections.

To switch from one section to another I don't use scroll but everything is done by clicking (menu, pagination, arrows, etc...)

As soon as the user goes on a section, the background changes color, each section to its color.

I have no problem creating this kind of function but I have a performance question.

Or perhaps it's a question of logic I dunno

It would be better if I bind my event on the scroll and ask for the color change as soon as the section is in the right position

window.addEventListener('scroll', requestAnimationFrame(function(){

    if ( sectionPosition === 0 ){


        // Do something...
    }
}))

or it would be better if I bind my events on the different clickable elements with event delegation

     window.addEventListener('click', function(event){
    let selector = event.target.getAttribute("href");


    if( selector === "#section-one"){

        //....
    }

    if(selector === "#section-two"){

        //....
    }
})

I think the second option is fine, adding listener on scroll will cause calling the callback with each px you scroll so make the action explicit is better than implicit with many unneeded calls

For the best you need to add click event listener on each element not on the whole window to avoid firing the click callback with any click.

To add click event on targeted item

const sectionOneEl = document.querySelector('#section-one');

sectionOneEl.addEventListener('click', ev => {
  // section one click handler
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM