Capturing scroll event on div

I am trying to capture a scroll event in Backbone.Marionette.CompositeView, but to no avail.

As an exercise, I rewrite http://www.atinux.fr/backbone-books/ with Backbone.Marionette. As you can see, when you scroll down, more books appear and are displayed (i.e., Infinite scrolling). However, I cannot capture the scroll event on my view.

Here is my (simplified) code:

LibraryView = Backbone.Marionette.CompositeView.extend({ // properties, initializer, etc. events: { 'scroll': 'loadMoreBooks', 'click': 'loadMoreBooks' }, // some functions loadMoreBooks: function(){ console.log("loadMoreBooks"); } }); 

The full source code can be seen here: https://github.com/davidsulc/backbone.marionette-atinux-books/blob/scroll/assets/javascript/app.js#L86-89

I do not understand that the click event fires correctly, but the scroll event does not. What am I doing wrong?


Edit: so the error was pretty simple at the end ... I passed "el: #content" to the view constructor, but the scroll was defined in CSS by ".library". Therefore, as soon as I changed my DOM from

 <div id="content"> <div class="library"> </div> </div> 

to

 <div id="content" class="library"></div> 

everything worked correctly ...

+3
source share
3 answers

This code works for me:

 var View = Backbone.View.extend({ events: { "scroll": "scroll" }, scroll: function(){ console.log( "scrolling..." ); } }); 

Check jsFiddle

As @JoshLeitzel said, I think the problem is in the DOM element itself.

Try backtracking:

 $("#content").bind( "scroll", function(){ console.log( "scrolling from jquery directly" ); } ); 

Also try replacing:

 el: $('#content') 

by

 el: '#content' 

I don't think this is a problem, but this is a new style for defining el :)

+7
source

The trunk joins the top el element to search for all events. Some DOM events do not fit into parent elements, and this includes scrolling. The click event worked because it bubbled.

Link: http://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#event-type-scroll

+16
source

I do not know what el , but I suspect that this event does not accept the scroll event. Since Backbone delegates jQuery event processing, look at what jQuery says about scroll event :

The scroll event is dispatched to an element when the user scrolls to another location in the element. It applies to window objects, but also for scrollable frames and elements using the CSS overflow set of properties to scroll (or auto when the element has an explicit height or width less than the height or width of its contents).

If your el does not satisfy these conditions, it will not receive a scroll event. You will need to place the event handler on the window or some other element that will receive it.

+4
source

Source: https://habr.com/ru/post/924595/


All Articles