简体   繁体   中英

Issue on IE adding class to a div via plain JavaScript on scrolling

I'm using the following javascript to perform adding a "sticky" class to "features-menu" div after scrolling down on browser certain amount.

Through search a while ago, I came across this code from another user I believe from stackoverflow, but cannot find that post to reference it. But I was looking for an example that does not use jQuery.

The following works great in Firefox, Chrome, and MS Edge browser but on IE11, the class doesn't seem to get added to the div.

Can anyone kindly suggest a fix for IE without using jQuery? Thank you so much!

<script type = "text/javascript" >

myID = document.getElementById("features-menu");

var myScrollFunc = function() {

  var y = window.scrollY;

  if (y >= 400) {
    myID.className = "sticky"
  } else {
    myID.className = ""
  }
};

window.addEventListener("scroll", myScrollFunc);

</script>

If you look in the web console, you'll see an error telling you that addEventListener isn't a function on older IE. And unfortunately, IE11 will hobble itself if you've looked at it funny, going into (in)Compatibility Mode, and not have addEventListener (or any of several other modern features). For instance, if your page is on an internal network, by default IE will use Compatibility Mode and act like IE7 — and fail because IE7 didn't have addEventListener .

You can test for that and use attachEvent instead:

if (window.addEventListener) {
    window.addEventListener("scroll", myScrollFunc);
} else {
    window.attachEvent("onscroll", myScrollFunc);
}

(Note the "on".)

This kind of browser inconsistency, combined with the DOM being quite verbose and awkward, is why we have libraries like jQuery. :-) (Not saying you should use jQuery [or any other lib], just saying this kind of thing is a major reason they exist.)

Note that attachEvent and addEventListener are not exactly the same, but both hook up events and for what you've shown, they'll behave the same. For a more thorough handling of the differences, see the hookEvent function in this answer .

The problem is with window.scrollY which is undefined in IE. This is an alternative approach :

Demo

var y = window.scrollY || window.pageYOffset;

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