Add/Remove Class with jQuery Based on Vertical Scroll
In this instance, the goal is to remove the class from the "header" element once the user scrolls down a certain distance, and then apply a different class to alter its appearance. However, the provided code isn't functioning as intended due to some minor errors.
The corrected code is as follows:
$(window).scroll(function() { var scroll = $(window).scrollTop(); // >=, not = 500) { // clearHeader, not clearheader - caps H $(".clearHeader").addClass("darkHeader"); } });
There were three main issues:
In addition to fixing these errors, consider the following:
if (scroll >= 500) { $(".clearHeader").addClass("darkHeader"); } else { $(".clearHeader").removeClass("darkHeader"); }
Finally, caching the jQuery object for the header can improve performance, especially if you plan to modify its class multiple times:
var header = $(".clearHeader"); $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 500) { header.removeClass('clearHeader').addClass("darkHeader"); } else { header.removeClass("darkHeader").addClass('clearHeader'); } });
By addressing these issues, you can now effectively add and remove classes from the header based on the user's vertical scroll position.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3