Elements on the page appear and disappear as you scroll down

Whenever my scroll reaches the bottom of element B, I want my hidden sticky element to appear. And when I scroll back up to the top of element B, the sticky element should be hidden again.

Here are my codes:

https://i.sstatic.net/J49dT.jpg

HTML

<html>
    <head>

    </head>
    <body>

        <ul class="sticky">
            <li><a href="#">Home</a></li>
            <li><a href="#">About Us</a></li>
            <li><a href="#">Download</a></li>
            <li><a href="#">Forums</a></li>
            <li><a href="#">Contact</a></li>
        </ul>

        <div class="container">
            <div class="a"></div>
            <div class="b"></div>
            <div class="c"></div>
        </div>

    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <body>
</html>

CSS

.container {
    width:1020px;
    margin:0 auto;
}
.container>div{
        width:100%;
        height:300px;
        background:#f0f0f0;
        border:1px solid #ccc;
        margin:100px 0;
    }
.a:after{
    content:"A";
    font-size:250px;
    text-align:center;
    line-height:300px;
    display:block;
    color:#999;
}
.b:after{
    content:"B";
    font-size:250px;
    text-align:center;
    line-height:300px;
    display:block;
    color:#999;
}
.c:after{
    content:"C";
    font-size:250px;
    text-align:center;
    line-height:300px;
    display:block;
    color:#999;
}
ul.sticky{
    list-style-type:none;
    padding:0;
    margin:0;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    background:#f0f0f0;
    height:50px;
    border-bottom:5px solid #ccc;
    display:none;
}
ul.sticky:after,ul.sticky:before{
    content:"";
    display:table;
    clear:both;
}
ul.sticky li a{
    display:block;
    float:left;
    line-height:50px;
    padding:0 30px;
    text-decoration:none;
    color:#999;
}
ul.sticky li a:hover{
    background:#999;
    color:#f0f0f0;
}

(I have a sticky element in my CSS that is initially hidden)

JQUERY

$(function() {
    $(window).scroll(function() {
        /* Unsure how to handle this scenario */
    });
});

Click here to view on CodePen

Answer №1

After some troubleshooting, I found a solution that worked for me. The element .sticky now appears after scrolling past the bottom of .b and hides when not visible:

$(function() {
    $(window).scroll(function() {
        if($(window).scrollTop() > $(".b").offset().top+$(".b").height()){
            $(".sticky").show();
        }else{
            $(".sticky").hide();
        }
    });
});

Answer №2

Recommended Solution:

To achieve the desired functionality, include the following jQuery snippet in your code:

$(function() {
    var targetOffset = $(".b").offset().top; // determine when the sticky element should appear
    var $w = $(window).scroll(function(){
        if ( $w.scrollTop() > targetOffset ) {
            $(".sticky").show(); // show the sticky element
        } else {
          $(".sticky").hide(); // hide the sticky element
        }
    });
});

When scrolling to the bottom of element B, the sticky element will become visible.

https://i.sstatic.net/2l1YR.png

Scrolling back up to the top of element B will hide the sticky element.

https://i.sstatic.net/GPKPj.png

Answer №3

To determine how far you are from the top of a document, check the scrollTop value and compare it with the element's scrollTop that you are scrolling to in order to know if you have reached it.

It is advisable to cache your selectors because the onScroll event can trigger frequently. If you constantly create jQuery objects and query the DOM within $.scroll(), it can be taxing on performance. To improve performance, consider adding a debounce or throttle function to limit the number of times the handler function is called during an onScroll event.

$(function() {

 var $sticky = $('ul.sticky');
 var bToTop = $('.b').scrollTop();

    $(window).scroll(function() {

if($(document).scrollTop() > bToTop){
$sticky.show();
}
else  {
$sticky.hide();
}
    });
});
.container {
width:1020px;
margin:0 auto;
}
.container>div{
width:100%;
height:300px;
background:#f0f0f0;
border:1px solid #ccc;
margin:100px 0;
}
.a:after{
content:"A";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
.b:after{
content:"B";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
.c:after{
content:"C";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
ul.sticky{
list-style-type:none;
padding:0;
margin:0;
position:fixed;
top:0;
left:0;
width:100%;
background:#f0f0f0;
height:50px;
border-bottom:5px solid #ccc;
display:none;
}
ul.sticky:after,ul.sticky:before{
content:"";
display:table;
clear:both;
}
ul.sticky li a{
display:block;
float:left;
line-height:50px;
padding:0 30px;
text-decoration:none;
color:#999;
}
ul.sticky li a:hover{
background:#999;
color:#f0f0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>

</head>
<body>

<ul class="sticky">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Download</a></li>
<li><a href="#">Forums</a></li>
<li><a href="#">Contact</a></li>
</ul>

<div class="container">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</div>

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<body>
</html>

If you only want to display the sticky element when you reach the end of element b, you can use

var bToTop = $('.b').height() + $('.b').scrollTop();

Answer №4

GitHub

$(window).on("scroll", function() {
   if ($(window).scrollTop() >= 800) {
     $("nav").css({"display":"flex"});
   } 
    if($(window).scrollTop() <= 800) {
     $("nav").css({"display":"none"});
   }
 });

Answer №5

This solution is the correct and optimal way to go.

To achieve the desired result, simply replace display: none with visibility: hidden;.

$(function() {
$(window).scroll(function() {
if ($(window).scrollTop() > $(".a").offset().top + $(".a").height()) {
$(".sticky").css({
"visibility": "visible"
});
} else {
$(".sticky").css({
"visibility": "hidden"
});
}
});
});
.container {
width:1020px;
margin:0 auto;
}
.container>div{
width:100%;
height:300px;
background:#f0f0f0;
border:1px solid #ccc;
margin:100px 0;
}
.a:after{
content:"A";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
.b:after{
content:"B";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
.c:after{
content:"C";
font-size:250px;
text-align:center;
line-height:300px;
display:block;
color:#999;
}
ul.sticky{
list-style-type:none;
padding:0;
margin:0;
position:fixed;
top:0;
left:0;
width:100%;
background:#f0f0f0;
height:50px;
border-bottom:5px solid #ccc;
visibility: hidden;
}
ul.sticky:after,ul.sticky:before{
content:"";
display:table;
clear:both;
}
ul.sticky li a{
display:block;
float:left;
line-height:50px;
padding:0 30px;
text-decoration:none;
color:#999;
}
ul.sticky li a:hover{
background:#999;
color:#f0f0f0;
}
.show{
display:block;
}
<html>
<head>

</head>
<body>

<ul class="sticky">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Download</a></li>
<li><a href="#">Forums</a></li>
<li><a href="#">Contact</a></li>
</ul>

<div class="container">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</div>

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the world of Node.js callback parameter passing

Currently, I am diving into the world of Node callbacks and JavaScript in general. As I delve deeper, I find myself puzzled by the following snippet: var request = require('request'); request('http://www.google.com', function (error, ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

Difficulties encountered when preserving the data of a website in HTML format

Usually, I request tweets on Twitter for a specific period and then scroll down the page to the last tweet. I save the HTML code of this page by right-clicking and selecting "Save As..." However, only the latest tweets are displayed in this HTML file. Is ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? https://i.sstatic.net/ZyYMM.png state c ...

What's the difference in width between Inline-Block and Float?

HTML <ul> <li><a href="#">Item #1</a></li> <li><a href="#">Item #2</a></li> <li><a href="#">Item #3</a></li> <li><a href="#">Item #4</a></li> & ...

What is the Reason for Wrapping Masterpage Javascript File References in a PlaceHolder Control?

While examining the demo project for xVal, a validation framework designed for ASP.NET MVC, I observed that the Masterpage javascript references were enclosed in a PlaceHolder control: <asp:PlaceHolder runat="server"> <script type="text/javas ...

The Divs pile one on top of the other

I am trying to position the second div below the first div instead of stacking on top of it and making the first div invisible. How can I achieve this? .shop { width: 100%; height: 1000px; background-color: #ffffff; position: relative; ...

Developing a RESTful API with Discord.js integrated into Express

Currently, I am faced with the challenge of integrating the Discord.js library into an Express RESTful API. The main issue at hand is how to effectively share the client instance between multiple controllers. The asynchronous initialization process complic ...

The system does not acknowledge NPM as a valid internal or external command

Here is the content of my package.json file for the server directory, which I am attempting to launch: { "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon src/app.js --exec 'npm ...

Transfer elements from collections employing multer

Data Payload Example:- education[0][university]: jru education[0][degree]: mca education[0][specialization]: computer application education[0][certificate_pdf_url]: (binary) education[0][degree_type]: Teaching Degree education[0][years_of_study]: [&q ...

The collapsing z-index menu in Bootstrap 4 is experiencing CSS issues and is not functioning correctly

I have a bootstrap 4 menu with a slide effect that is functioning correctly, but there seems to be an issue with the z-index value I have set for it. Specifically, there is some content within a parallax jumbotron that is overlapping the menu links. I need ...

Error: The function cannot be called because it is undefined

As a newcomer to JavaScript, I recently copied a script from jqueryui.com for the dialog widget and pasted it into my Yii project. However, upon testing the code, I encountered an error: Uncaught TypeError: undefined is not a function associated with the ...

The material icons CDN does not seem to be functioning properly in Next.js

After adding a CDN to the head section of my Next.js project, I encountered an issue where it was not working as expected. import Head from "next/head"; <Head> <link href="https://fonts.googleapis.com/icon?family=Material+Ico ...

Is there a way to retrieve the intersection point (Vector3) of the intersectObjects?

I need assistance in finding the point where a ray cast from 'child' intersects with a mesh (child2) using Raycaster: var raycaster = new THREE.Raycaster(); var meshList = []; meshList.push(child2); for (var i = 0; i < child.geometry.vertices ...

Issue with border radius not applied to input-group in Bootstrap 3

Can anyone explain why the input-group in Bootstrap 3.4 is missing all border radius? <form action="{{ route('dashboard.users.index') }}" method="get"> <div class="input-group"> <input type="text" name="search" class="f ...

The ReactCSSTransitionGroup does not insert any additional classes

I have been attempting to incorporate animation into each list item within a list of articles that I am loading through an ajax request. Despite my efforts, the ReactCSSTransitionGroup element does not seem to be functioning as expected on the targeted ite ...

Catching exceptions with jQuery Ajax

I'm facing a tricky issue with an exception that seems to slip through my fingers: //myScript.js.coffee try $.ajax async: false type: "GET" url: index_url success: -> //Do something error: -> //Do something els ...

How can a variable that is potentially undefined be converted to lowercase in Node.js?

My latest project involves developing a discord.js bot with commands that can take different parameters like mc!start vanilla, mc!start tekkit. However, the bot is designed to handle only singular string entries. So, when a user inputs just mc!start with ...