user962206
user962206

Reputation: 16127

JQuery event is still being loaded even if the DOM has been removed

I have this markup

  <html>
     <body>
       <div id ="wrap">
         <div id = "main-content">
           <!-- more markup here -->
           <script>
          $(window).scroll(function(){
           if($(window).scrollTop() >= ($(document).height() $(window).height())*0.7) {
               alert("SCROLLED") 
             }}); 
           </script>
         </div>
       </div>
     </body>
    </html>

and I am usually doing ajax calls to remove the contents of "main-content" and I do that using this

   $.get(sampleUrl, function(data) {
        var newTitle = $(data).filter('title').text();
        $('#main-content').children().remove();
        $('#main-content').html($(data).find('#main-content').html());
    },"html");

However the above code removes only the DOM not the javascript events like "scroll" event, is there anyway I can remove/unbind it?

Upvotes: 0

Views: 62

Answers (3)

user56reinstatemonica8
user56reinstatemonica8

Reputation: 34084

$(window).unbind('scroll');

The event is bound to the window - where on the page the script tag was makes no difference after the code is executed and the event is bound.


Actually unbind() is the old-school way, these days $(window).off('scroll'); is "preferred" - unless you're stuck using a legacy version of jQuery older than 1.7. unbind() still works, ain't deprecated yet, but there's always the chance it might be.

Upvotes: 1

Dave Stein
Dave Stein

Reputation: 9316

When a script tag is put on the page it executes. It will make an eventListener for scrolling on the window. Removing any content inside main-content will not undo a listener, and your window will obviously still exist.

You want to call $(window).off('scroll') when you want that behavior to stop.

$(window).unbind is an older way of doing things that is deprecated.

Sidenote:

You want to avoid putting inline JS if you can.

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 190942

$(window).off('scroll') should do the trick.

Upvotes: 1

Related Questions