Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .on('scroll') not firing the event while scrolling

Scroll event is not firing while scrolling the ul. I'm using jQuery version 1.10.2. As I'm loading the ul from an ajax page, I couldn't use $('ulId').on('scroll', function() {}); or other live methods. Please help me to find a solution.

$(document).on( 'scroll', '#ulId', function(){     console.log('Event Fired'); }); 
like image 972
ABHILASH SB Avatar asked Oct 15 '13 07:10

ABHILASH SB


People also ask

Does scrollIntoView trigger scroll event?

scrollIntoView does not trigger mousewheel nor scroll event in Angular. Bookmark this question.

What is scroll event in jQuery?

The scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

How do you stop an Onscroll event?

The window. onscroll event fires when the window has been scrolled. Overriding this function and setting it to a fixed position every time the scroll happens will effectively disable the scroll effect.


2 Answers

You probably forgot to give # before id for id selector, you need to give # before id ie is ulId

You probably need to bind the scroll event on the div that contains the ul and scrolls. You need to bind the event with div instead of `ul`
$(document).on( 'scroll', '#idOfDivThatContainsULandScroll', function(){     console.log('Event Fired'); }); 

Edit

The above would not work because the scroll event does not bubble up in DOM which is used for event delegation, see this question why doesn't delegate work for scrolling.

But with modern browsers > IE 8, you can do it in another way. Instead of delegating by using jquery, you can do it using event capturing with javascript document.addEventListener, with the third argument as true; see how bubbling and capturing work in this tuturial.

Live Demo

document.addEventListener('scroll', function (event) {     if (event.target.id === 'idOfUl') { // or any other filtering condition                 console.log('scrolling', event.target);     } }, true /*Capture event*/); 

If you do not need event delegation then you can bind scroll event directly to the ul instead of delegating it through document.

Live Demo

$("#idOfUl").on( 'scroll', function(){    console.log('Event Fired'); }); 
like image 138
Adil Avatar answered Sep 28 '22 08:09

Adil


Binding the scroll event after the ul has loaded using ajax has solved the issue. In my findings $(document).on( 'scroll', '#id', function () {...}) is not working and binding the scroll event after the ajax load found working.

$("#ulId").bind('scroll', function() {    console.log('Event worked'); });  

You may unbind the event after removing or replacing the ul.

Hope it may help someone.

like image 27
ABHILASH SB Avatar answered Sep 28 '22 06:09

ABHILASH SB