Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What is the difference between the following?

$(document).on("scroll",".wrapper1", function(){
   $(".wrapper2")
    .scrollLeft($(".wrapper1").scrollLeft());
});  

$('.wrapper1').on("scroll", function(){
        $(".wrapper2")
            .scrollLeft($(".wrapper1").scrollLeft());
});

When to should each functions be used exactly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
433 views
Welcome To Ask or Share your Answers For Others

1 Answer

The difference between these two are

$('.wrapper1').on("scroll", ....) binds the scroll event to only those elements which are present at the time of execution of this statement, ie if any new element with class wrapper1 is added dynamically after this statement is executed then the event handler will not get executed for those elements.

$(document).on("scroll",".wrapper1", ...) on the other hand will register one event handler to the document object and will make use of event bubbling to invoke the handler whenever scrolling happens within an element with class `wrapper``, so it will support dynamic addition of elements.

So when to prefer a method

you can prefer first method if you have only a limited number of elements and they are not dynamically added

Prefer the second method if you have lot of elements or these elements are added dynamically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...