If you have an element that is sticky on the page, such as a call to action button, toggle links visibility based on the scroll position of the page could be a simple way to make it pop out and get more interaction. In this article, we will show you how to toggle the visibility of any element based on the scroll position of a page. This answer will use vanilla JavaScript, but will link you to a resource that describes several other ways to do this.
Here's the code that we're going to use to toggle the visibility of an element depending on how far the user is scrolled down the page. In this example, the element remains hidden until the user has scrolled 800 pixels down the page, meaning that they are quite interested in the content, and dynamically popping up a call to action button in the lower right hand corner may lead to a conversion event.
myID = document.getElementById("customID");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
myID.className = "cta show"
} else {
myID.className = "cta hide"
}
};
window.addEventListener("scroll", myScrollFunc);
Code language: JavaScript (javascript)
With this answer, we need to incorporate some custom CSS which dictates the visibility of the element.
.cta {
position: fixed;
bottom: 20px;
right:20px;
width: 60px;
height: 60px;
border-radius:50%;
background: red;
z-index: 1;
transition: all 1s;
}
.hide {
opacity:0;
left:-100%;
}
.show {
opacity:1;
left:0;
}
Code language: CSS (css)
The code essentially states that the element (identified by its ID and class) will have the hidden class applied to it until the scroll position is greater than 800 pixels. The hidden class in CSS has an opacity of zero. Once the scroll position exceeds 800 pixels, the hidden class is changed to the show class, which has an opacity of 1, making it visible on the screen.
The CTA itself starts out looking like this:
<div id="customID" class="cta hide"></div>
Code language: HTML, XML (xml)
This code was grabbed and adapted from this incredible StackOverflow answer, Which has tons of more detailed information if you are interested in using JavaScript (or jQuery) to dynamically show and hide elements based on the scroll position of a page.
In that same answer, the commenter posted the following jQuery code, which is a bit easier to use than vanilla JavaScript, and works on WordPress as JavaScript is already included.
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 800) {
$('.<em>cta</em>').fadeIn();
} else {
$('.<em>cta</em>').fadeOut();
}
});
Code language: JavaScript (javascript)
Here, the only thing you need to adapt is the number of pixels needed to toggle the visibility of the element, and the class name of the element.
This is a better solution because it doesn't require any additional CSS show/hide classes. However, you do need to initially set the element to not display, like so:
.cta {
display: none
}
Code language: CSS (css)
thank you so much dude, you're awesome!!!!!
it worked 😀