Display the mobile Navbar only when scrolling to the top (using Bootstrap 4)

My goal is to have the navbar on mobile only appear when the user scrolls to the top of the page.

Currently, it remains fixed at the top regardless if the user is scrolling up or down. I found this code snippet here: Here's a live example:

This is my JavaScript code:

new IntersectionObserver(function(entry, observer){
        if (entry[0].intersectionRatio > 0){
            document.documentElement.removeAttribute('class');
        } else {
            document.documentElement.setAttribute('class','stuck');
        };
    }).observe(document.querySelector('.trigger'));

Update: just to clarify my objective:

The mobile navbar should not be sticky, but instead scroll with the rest of the content. However, when scrolling from the bottom to the top of the page, I want the navbar to appear at the top and remain there until scrolling back down.

Answer №1

Applying the CSS media query to target mobile devices with a screen width of less than 768px is a common practice when using the position:sticky property...

.sticky-top {
    position: static;
}

@media (max-width:768px) {
    .sticky-top {
        transition: all 0.25s ease-in;
        position: sticky;
    }

    .stuck .sticky-top {
        background-color: #222 !important;
        padding-top: 3px !important;
        padding-bottom: 3px !important;
    }
}

To achieve the opposite effect of having a non-sticky navbar on mobile, simply reverse the media query by using min-width instead of max-width...

@media (min-width:768px) {
    .sticky-top {
        transition: all 0.25s ease-in;
        position: sticky;
    }

    .stuck .sticky-top {
        background-color: #222 !important;
        padding-top: 3px !important;
        padding-bottom: 3px !important;
    }
}

Answer №2

By using the "sticky-top" class, you can make the navigation bar stay at the top of the page while the user scrolls. Removing this class should resolve the problem you're facing.

See an example in action here:

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

Encountering the "Unexpected token SyntaxError" message is a common issue that arises while trying to import express-handlebars

Whenever I include this specific line, an error shows up. But as soon as I remove it, the error disappears. const expressHandleBars = require('express-handlebars'); The error message goes something like this: C:\Users\Hp\sample- ...

Steps to eliminate the 'Edit Translation' text on Transposh

Attempting to eliminate the 'Edit Translation' text provided by Transposh to maintain the existing translations. Implementing CSS code like so: #transposh-3:nth-child(8){display:none;} and localizertextnode{display:none;} However, these styl ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Show the output of a jQuery query in a label within an ASP.NET page

Is there a way to display the result of this JavaScript code in a label control on my ASP.NET page, instead of using an alert? <script type="text/javascript" language="Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"& ...

How do I ensure that my absolutely positioned element is centered in this specific scenario?

I've been working on centering an element within its parent container, and I'm having trouble ensuring it remains centered responsively. Here's what I have so far: HTML <div class="example"> <span class="element1">Element ...

What might be causing my direct descendant selector to not work as expected?

I'm struggling with my direct descendant selector. Let's analyze a straightforward example: .myDiv > table tr:first-child td { font-weight: bold; text-align: center; } <div class="myDiv"> <table style="width:100%"> < ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Access + authentication code

After successfully using my login script in Postman, I ran into issues when attempting to integrate it with React.js for posting to the server. The problem lies in the fact that when the script checks for the user, it fails to return the return result. It ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

What could be causing the imperfections in the circle around this item

I am currently working on customizing the <p-calendar> tag from primeng 6.1.1. My goal is to have a blue circle appear when hovering over the month item. I envision it looking like this: https://i.sstatic.net/wZ41wm.png However, what I am getting i ...

generate an electronic communication using an HTML and PHP template

Currently, I am working on a PHP web application that requires sending emails in HTML format. To achieve this, I am utilizing the mail() function. My goal is to send emails based on a template file that is formatted in HTML and includes segments of PHP ...

Email confirmation section

I'm in the process of setting up a subscription newsletter page, and everything seems to be working correctly except for the part where I need users to enter their email address twice. The second email field is meant for confirmation purposes, but I&a ...

The <button> tag and the <a> tag have different display properties

I am in the process of creating unique custom buttons using CSS. Below is the code snippet that I have created for this purpose. Interestingly, when I apply the CSS to a <button> element, it behaves as expected. However, when I use it with an <a& ...

Table with checkboxes for row selection

Hey there, I've just set up a table with some values. My goal is to select all checkboxes with the first checkbox and uncheck them. print "Content-type: text/html; charset=iso-8859-1\n\n"; my $script = qq{ \$('#id').change(fu ...

Construct an array through the power of Ajax

Currently, I am facing an issue with building an array using ajax. The 'test' array is structured correctly, but the 'translations' array has a flawed structure (as seen in my console output). In Chrome console: https://i.sstatic.net/m ...

Having trouble retrieving data from the input fields with jQuery

My handlebars file looks like this: <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="login-form"> <form class="form-horizontal well"> <div class="form-group"> ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

The ng-repeat function is unable to fetch data from a JSON file

Within my AngularJS framework template, I have the following snippet of html code: <ul class="sb-parentlist"> <h1 class={{headerClass}}> Popular</h1><div data-ng-repeat="data in data track by $index"> <li> ...

Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeli ...