Intelligent Scrolling with Bootstrap 4

Utilizing a basic tutorial from here to implement show/hide functionality for a standard BS4 navbar on scroll. Works flawlessly on desktop.

However, facing an issue with the mobile view where the navbar behaves oddly when scrolling down and returning to the top. Upon reaching the top again, the navbar disappears once more.

Suspecting that the problem lies within the scrollTop() function but unable to pinpoint the exact cause of the issue.

Sharing my JS code below:

    if ($('.smart-scroll').length > 0) { // check if element exists
        var last_scroll_top = 0;
        $(window).on('scroll', function() {
            var scroll_top = $(this).scrollTop();
            if(scroll_top < last_scroll_top) {
                $('.smart-scroll').removeClass('scrolled-down').addClass('scrolled-up');
            } else {
                $('.smart-scroll').removeClass('scrolled-up').addClass('scrolled-down');
            }
            last_scroll_top = scroll_top;
            /* Tried to catch for scroll_top zero, but doesn't help */
            if(scroll_top == 0) $('.smart-scroll').removeClass('scrolled-up');

        });
    }

Additionally, presenting my CSS styles:

.smart-scroll {
    position: fixed !important;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease-in-out;
}
.scrolled-down {transform:translateY(-100%);}
.scrolled-up {transform:translateY(0);} 

Even attempted integrating suggestions from this stackoverflow thread without success.

Any insights on how to resolve this issue for mobile devices?

Answer №1

Had a similar scenario in my projects, and I was able to modify the code to suit your specific requirements.

if ($('.smart-scroll').length > 0) {

        var lastScrollTop = 0;
        $(window).scroll(function() {    

            var scroll_top = $(window).scrollTop();

            if (scroll_top > 1) { // tweaking this condition a bit could help catch scrolltop more effectively 
                $(".smart-scroll").addClass("stick");
            } else { 
                $(".smart-scroll").removeClass("stick");
            }

            if (scroll_top > lastScrollTop){
                $(".smart-scroll").removeClass("scrolled-up");                      
            } else {
                $(".smart-scroll").addClass("scrolled-up");
            }                       
            lastScrollTop = st;

    });

}   

Also, here is the accompanying CSS:

.smart-scroll {
    position: fixed !important;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease-in-out;
    transform:translateY(0);
}
.stick {transform:translateY(-100%);}
.scrolled-up {transform: translateY(0) !important;} 

Answer №2

To ensure it doesn't disappear at the top, I included this code after the if/else statement.

if(scroll_top <= 0) {
   $('.headerContainer').removeClass('scrolled-up').removeClass('scrolled-down');
}

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

Unusual sizing of text input in jQuery Mobile

I've encountered an issue regarding the width of a text input in jQuery Mobile - it appears to be too large. <div data-role="page"> <div data-role="header"> <h1>Test</h1> </div> <div data-role="co ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...

Issue with dynamic imports in express routes

I am currently attempting to incorporate a dynamic import within an express.js router Here is the code snippet I have: HelloWorldController.js export const helloWorld = function (req, res) { res.send('hello world') } router.js export defa ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

How can pagination be implemented with a line chart in Chart.js?

I'm dealing with a large amount of data - around 10,000 rows that I need to display in a line chart. I'm looking for a pagination system where users can click on an arrow to show the next 20 data points, and so on. Currently, my app crashes when ...

"Material-Table does not have the ability to insert a new row

Just started learning JS and React. I'm attempting to integrate Material-table with an add row button, but encountering issues where the added row is not reflecting. Every time I refresh the page, the rows are reset. I suspect there's a problem w ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...

Arrangement of HTML divs and styling classes

I have been experimenting with divs and classes in order to achieve proper alignment of text on my website. Currently, I am working with 2 classes that I would like to display side by side to create 2 columns. However, the right column containing the text ...

triggering a method in an Angular controller using a Google API embedded in the view

Using the Google Places Details API, I have included a Google API with a callback function called initMap in the src attribute. Here is the code snippet: <div class="tab-pane active" id="timeline"> <p class="lead">Location</p> <hr& ...

Differences Between Using WebDriver click() and JavaScript click()

The Scenario: Within the realms of StackOverflow, instances have been observed wherein users encounter difficulties clicking on an element through selenium WebDriver's "click" command. As a solution, they resort to using a JavaScript click by executi ...

Tips for circumventing the restriction of the 'no-param-reassign' regulation when working with the handleChange function for inputs

Currently, I am developing a React Textarea component that automatically grows or shrinks based on user input. The code for my component was inspired by this particular codepen: https://codepen.io/Libor_G/pen/eyzwOx Although the functionality works smooth ...

Is there a way for the window.onbeforeunload event to wait for an ongoing animation to finish

Exploring the JavaScript code below which utilizes an animation library (such as scriptaculous). window.onbeforeunload = function(event) { document.body.fade(); } When leaving the page, the animation does not finish before the page changes. This raise ...

Utilizing Ajax/jQuery to Send Variables to PHP

I'm having a bit of trouble with a simple task. I'm using a jQuery script to show a timer and then I want to send the number of seconds to a PHP file. When I alert the value variable, it shows the correct data, so I know I'm accessing it cor ...

I encountered a height discrepancy when attempting to style an unordered list to resemble a table

I have created a set of ul lists that appear as a 2-column table, just as I needed. However, an issue arises when the content of any list increases. The problem is that equal height is not being applied, causing the table to look broken. Here is my Fiddle ...

Adding an element to a blank array using Angular

When attempting to add a new item to an empty array, I encounter an error: $scope.array.push is not a function. However, when the array is not empty, the push operation works flawlessly and updates my scope correctly. Just so you know, my array is initia ...

Tips on managing URL in jQuery Mobile that appears in the navigation bar

I am currently working on a jQuery Mobile application that is designed to function on a single static URL, also known as a single page application. Using $.mobile.changePage.defaults.changeHash = false within the mobileinit event has been successful in ma ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Display the list box against the masked background

I currently have a masked background and a drop-down hidden behind it. Here is how it appears: https://i.sstatic.net/QTLN5.png However, I want it to look like this: https://i.sstatic.net/ZAreM.png This is the HTML code being used: <div id="sugges ...

Eliminate styling from text within an HTML document

I'm currently working on removing text decorations from my text. I managed to remove the underline, but when I hover over the text, the color still appears. How can I get rid of this color as well? Take a look at the code below: messbox { backgr ...

Transform the code to utilize AJAX jQuery

Recently, I developed a Chrome Extension that extracts data from the data-href attribute and applies it to the href attribute from a Google Search. Below is the current implementation: $(document).on("DOMSubtreeModified", function() { var e = $("#sear ...