Reputation: 1
so i found this js somewhere, which is working perfectly fine. But how can i add this funtion to a diffrent class without overwriting it? like i want to use the same funtion but for a diffrent object in my html, so that i can use the same effect again just at a diffrent viewpoint and with a diffrent object on my page.
$(document).scroll(function() {
myID = document.getElementById("advertisement");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 550) {
myID.className = "advertisement show"
} else {
myID.className = "advertisement hide"
}
};
window.addEventListener("scroll", myScrollFunc);
});
i tried to just copy paste it and create a new variable but im a js beginner so had no luck with that
Upvotes: 0
Views: 111
Reputation: 206593
You don't need the jQuery scroll event. Only the inner JavaScript one.
Also, use classList.toggle("className", force) instead:
const elAdvertisement = document.querySelector("#advertisement");
const toggleAdvertisement = () => {
elAdvertisement.classList.toggle("hide", scrollY < 550);
};
addEventListener("scroll", toggleAdvertisement); // On scroll
toggleAdvertisement(); // On init
body {
min-height: 1000vh; /* just to force scrollbars */
}
#advertisement {
position: fixed;
top: 0;
}
.hide {
display: none;
}
Scroll down
<div id="advertisement" class="hide">ADVERTISEMENT HERE</div>
If you are using jQuery, here's a code sample with that library:
const $advertisement = $("#advertisement");
const toggleAdvertisement = () => {
$advertisement.toggleClass("hide", scrollY < 550);
};
$(document).on("scroll", toggleAdvertisement); // On scroll
toggleAdvertisement(); // On init
body {
min-height: 1000vh; /* just to force scrollbars */
}
#advertisement {
position: fixed;
top: 0;
}
.hide {
display: none;
}
Scroll down
<div id="advertisement" class="hide">ADVERTISEMENT HERE</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Upvotes: 1