I am trying to create a sticky button which shows up when scrolling down for 100px, but I have problems to figure out whats wrong with the code. First I thought it is because of Wordpress and I need to fix something there because I use a custom html element and additional css, but I got back an error from the console.
HTML:
<div id="sticky-cta" class="sticky-cta hide">
<button>Click here</button>
<p><i>Some text here</i></p>
</div>
It doesn’t like the $ - is this a copy-paste from somewhere? The dollar sign is normally an indicator of the jQuery library. Are you calling that in?
@snowmonkey No I am not calling JQuery and yes it is an example copy and paste code.
I miss the understanding for the right syntax, so I can just try and error until I go crazy. I can also searching for another code example which works, but I think it is just a tiny little syntax error
$(...).scroll() is a jQuery specific function, used to scroll the viewport to a particular page position.
Seems to me there are two possible fixes: short-term, add a script tag to add the jQuery library, or long-term learn to code the scrolling effect in plain javascript, removing the jQuery $ reference.
Each has pros and cons, and depends on your intent: are you trying to make this work asap, or are you trying to learn javascript?
Oh I did not know that $(...).scroll() is a jQuery specific function, thanks for letting me know. Actually I never worked with jQuery and there are a lot of opinions around the web that it is not worth learning jQuery anymore… I love CSS and I like to style everything individual by myself if this makes sense…
I am learning JavaScript from the ground on, but it takes time and I need the solution as soon as possible, so it would be great if you have a hint for me how to solve this. In my opinion the code below the first line is correct, so I guess I just need to change the first line which declares a function?
Edit: Maybe I dont even need the first line, I already declared a function var myScrollFunc = function () and I grab the html elements by .getElementById, so what is missing here?
<script>
myID = document.getElementById("sticky-cta");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 800) {
myID.className = "sticky-cta show"
} else {
myID.className = "sticky-cta hide"
}
};
window.addEventListener("scroll", myScrollFunc);
</script>
But the problem now is that when I first open the website then the element is visible, when I scroll down and up again the element disappears. The element should not be visible when I first open the website, it should just be visible when someone scrolls down.
When I look at the code I dont understand why the element also shows up when the website opens the first time, because Y needs to be greater then 800px to show the element and when the website opens the first time Y is less then 800px.
I thought this happened because the <script> tag is not in the header, but when I put it in the header then it is not working…