简体   繁体   中英

How to stop scroll event function when the user move to another page

I am adding the scroll event in javascript for one of my pages. The code is like this:

    document.getElementById("myProject").addEventListener("scroll", myFunction);

     function myFunction() {
     document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";

     }

So, when users start scrolling, they will see a text "These are all my projects so far".

My problem is how to stop showing this text when users move to another page.

Please help ( I am a verrrry fresh developer) Thanks so much

A few thoughts.

  1. Without knowing your dev environment (eg are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.

  2. Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.

  3. If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.

If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.

If the case is a switching between browser tabs, you can use two different events like below.

$(window).blur(function(e) {
  // stop scroll event, when switching to another tab
  document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
  // start scroll event
  document.getElementById("myProject").addEventListener("scroll", myFunction);
});

I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.

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