Trigger multiple classes within js funtion - javascript

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

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>

Related

show and hide toTopButton according the scrolling but window.onscroll not work ..i can not fix the real problem

Please I need your support as I write this code to create a button and when I press it I move to the top of page ...the button is created good and move to top of page ... But I want the button hide when the scrolling in the top of page and appear again when I scroll down ...the scroll function not work I do not know the reason … I support you with the code in JavaScript and CSS related to my question …you are genius if you can fix it.
First JavaScript code
//here i create a function to make scroll smooth...i can write it in css file but i want to show what is i lrarned:
const scrollSmoothly = function () {
const myHTML = document.querySelector("html");
myHTML.style.scrollBehavior = "smooth";
};
//create the to Top Button
//
scrollSmoothly();
function toTopButton_create() {
const toTopButton = document.createElement("botton");
const textnodeTOP = document.createTextNode("TO_Top");
toTopButton.appendChild(textnodeTOP);
//document.querySelector("footer").appendChild(toTopButton);
const rr = document.querySelector("footer");
rr.insertAdjacentElement("beforebegin", toTopButton);
toTopButton.setAttribute("id", "ourBtn");
toTopButton.addEventListener("click", test2);
}
toTopButton_create();
//below function to go to the top of sheet
function test2() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// below function to hide the (to top button) in the top and appear again when we scroll down
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
CSS code
#ourBtn {
padding: 16px;
right: 31px;
bottom: 10px;
font-size: 19px;
z-index: 98;
border-radius: 5px;
border: none;
outline: none;
display: block;
background-color: rgb(17, 199, 231);
color: rgb(29, 2, 2);
position: fixed;
cursor: pointer;
}
#ourBtn:hover {
background-color: rgb(219, 8, 8);
}
Note : when I change in CSS code and make display: none; the button hidden and when I change it to display: block; it appear again …this is not problem ...the real problem that the (to top button) not appear and hidden according to the scrolling ... I think the scroll function not work. Thanks for your support in advance.
Change this part of your code
// below function to hide the (to top button) in the top and appear again when we scroll down
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
To this
// below function to hide the (to top button) in the top and appear again when we scroll down
document.onscroll = scrollFunction;
function scrollFunction(event) {
if (event.srcElement.scrollingElement.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
Note:
Attach the event to the document object
Look for the scrollingElement (it might not be the body element)
The main problem in my code was the variable (toTopButton) this variable defined in the function ,so it is not declared or defined out the function ...when I create it a gain in the global area ...the function worked good

add className on scroll in JavaScript

I'm trying to add a className on scroll. I keep getting a
document is undefined
edit: I found out I was getting the error from the typo. When I define document.getElementsByClassName("main-nav").scrollTop nothing comes up in the console. As well as the page does not get affected.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav").className = "test";
} else {
document.getElementsByClassName("main-nav").className = "";
}
}
CSS is
.test {
background: pink
}
I'm not necessarily looking for the answer, I just want guidance
There are 2 problems:
getElementsByClassName returns an array of HTMLCollection and it has no property scrollTop. You probably want the first item so the code shoul be document.getElementsByClassName("main-nav")[0] (or document.querySelector(".main-nav"))
But if you try it, you will get an error:
Cannot read property 'scrollTop' of undefined
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav").className = "test";
} else {
document.getElementsByClassName("main-nav").className = "";
}
}
html, body {
height: 150%;
}
.test {
background: pink
}
<div class="main-nav"></div>
The reason is that you override the class attribute of .main-nav by this assignment:
document.getElementsByClassName("main-nav").className = "";
In this line you set the class attribute to empty string. You probably want to add / remove the test call but keeping the main-nav class.
There are 2 things you can do:
Set the id attribute to main-nav instead of the class attribute, then use document.getElementById method.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementById("main-nav").scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("main-nav").className = "test";
} else {
document.getElementById("main-nav").className = "";
}
}
html, body {
height: 150%;
}
#main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div id="main-nav">Main Nav</div>
Toggle only the test class using classList.toggle.
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
if (document.getElementsByClassName("main-nav")[0].scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementsByClassName("main-nav")[0].classList.add("test");
} else {
document.getElementsByClassName("main-nav")[0].classList.remove("test");
}
}
html, body {
height: 150%;
}
.main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div class="main-nav">Main Nav</div>
The final approach with some optimisations:
var mainNav = document.querySelector('.main-nav');
window.onscroll = function() {
windowScroll();
};
function windowScroll() {
mainNav.classList.toggle("test", mainNav.scrollTop > 50 || document.documentElement.scrollTop > 50);
}
html, body {
height: 150%;
}
.main-nav {
position: fixed;
width: 100%;
}
.test {
background: pink
}
<div class="main-nav">Main Nav</div>
The changes:
Store the .main-nav element on the global context (the window object). It will not change so you don't need to find it in any scroll.
Use querySelector so you will get a single DOM element, not collection.
Use classList.toggle to toggle the class by condition.
The issue with your console.log is that you're trying to pull the scrollTop for an HTML Collection (a collection of elements in your page) of 1 or more divs - therefore it can't check for the scrollTop as the console.log as it doesn't actually have that property.
Assuming you only have one element with the "main-nav" class (or there is a particular element with this class that you wish to apply it to), you would be better off using one of the following: document.getElementsByClassName("main-nav")[0] or document.getElementById("main-nav") (the latter would require you to create a main-nav id rather than a class).
For the first one, however, using className reassigns the class name rather than adding to that particular div, therefore you can use document.getElementsByClassName("main-nav")[0].classList.add("test") (and remove instead of add if it does not match your criteria).
If there is more than one element with the "main-nav" class, you can still use the first option I suggested - only you would need to wrap it around in a for loop and replace the 0 with your variable of choice.
for (i = 0; i < document.getElementsByClassName("main-nav").length; i++) {
//your code here using document.getElementsByClassName("main-nav")[i]
}

Scroll event bind using addEventListener on body does not work. Why?

In the following, the javascript's scroll event does not call the function counter() when the page is scrolled. Why?
JS
$(function(){
var body = document.getElementsByTagName('body');
body[0].addEventListener('scroll',counter, true);
var x = 0;
function counter() {
document.getElementById("demo").innerHTML = x += 1;
}
});
HTML
<div id="demo"></div>
set height property to the document, to make the scroll event actually possible
body[0].addEventListener('scroll', counter, true) won't make any effects. body tag is the whole document - refer to the document instead
it can be done without using jQuery
(function() {
document.addEventListener('scroll', counter, true);
var x = 0;
function counter() {
document.getElementById("demo").innerHTML = x += 1;
}
})();
body {
height: 1000px;
}
#demo {
position: fixed;
}
<div id="demo"></div>
Add the scroll event to the global window object and make sure that a scrollbar is actually visible so that the scroll event fires.
Check the below code snippet.
$(function() {
var x = 0;
window.addEventListener('scroll', counter, true);
function counter() {
document.getElementById("demo").innerHTML = x += 1;
}
});
body {
height: 1000px;
background-color: #E6E6E6;
}
#demo {
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="demo"></div>
Check this for more information

Display some element user scrolling

I would like to display some element (div for example) when the user scrolling.
I seeing that a scrollTop, but isn't work. Because for sure I use badly.
I can't find some help without JQuery. I don't want to use JQuery.
I try this :
var scroll = document.body.scrollTop;
var divLis = document.querySelectorAll("div");
for(let i = 0; i < divLis.length; i++) {
if(scroll === divLis[i]) {
divLis[i].style.transform = "translateX(0)";
divLis[i].style.transition = "2s";
}
}
I honestly can't really tell what you're trying to do, but given your response to #uom-pgregorio's answer, I'm guessing you might just want a pure JS scroll listener:
window.addEventListener('scroll', function() {});
Edit: Sorry I just noticed that you didn't want jQuery but I'll just leave this here in case you change your mind.
$(window).scroll(function() {
// show the div(s)
});
That's an event handler where the function runs or fires up whenever the window or viewport scrolls.
Ok... I understand.
I wanted to try this :
* {
margin: 0;
padding: 0;
border: 0;
}
body {
height: 200vh;
}
.left {
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: 150%;
transform: translateX(-300px);
transition: 5s;
}
// HTML :
<div class="left"></div>
// JS
var divLis = document.querySelector(".left");
window.addEventListener("scroll", function (e) {
if(window.pageYOffset > 500) {
console.log(window.pageYOffset)
divLis.style.transform = "translateX(0)";
}
})
So, it's very simple and I took my head for nothing.
So thanks so much for answering me !
Enjoy your Weekend

Jquery Simple ScreenSaver

Hello guys reading this article i create simple screensaver, but i got one problem, when i let my mouse stop i need to hide one div and show other, but when div shows animation stop, what is my problem, my code
var mousetimeout;
var screensaver_active = false;
var idletime = 5;
var screenSaver = $("#screenSaverForm");
var formDiv = $("#bodyForm");
function show_screensaver() {
formDiv.fadeOut(100);
screenSaver.fadeIn(900);
screensaver_active = true;
}
function stop_screensaver() {
screenSaver.fadeOut(100);
formDiv.fadeIn(900);
screensaver_active = false;
}
$(document).mousemove(function () {
clearTimeout(mousetimeout);
if (screensaver_active) {
stop_screensaver();
}
mousetimeout = setTimeout(function () {
show_screensaver();
}, 1000 * idletime); // 5 secs
});
and divs:
<div id="screenSaverForm" style="background-image: url(../../Content/img/screensavers.jpg); position: absolute; width: 100%; height:100%; left:0px; top: 0px; display: none; z-index:9999; display: none;">Example of a DIV element with a background image:</div>
Other div is simple, and if any can help, before show animation i need to reload page, any knows how to do this?
You could try adding this line in before stop_screensaver();
.
...
if (screensaver_active) {
location.reload(); //Refreshes the page
stop_screensaver();
}
...
.
Or, if you just want to scroll to the top of the page:
.
...
if (screensaver_active) {
$(window).scrollTop(0); //Scroll to top of page
stop_screensaver();
}
...
.

Categories

Resources