Showcasing Bootstrap navigation exclusively on mobile devices and including a scroll function on desktop screens

I am working on customizing a Bootstrap 4 top-sticky nav to only be visible on mobile devices. Using CSS (d-block d-md-none) can achieve this, but on desktop, I want the menu to fade in as the user scrolls down past a certain point and disappear when scrolling back up. However, my current implementation causes the menu to briefly show on load on desktop.

(function ($) {
  $(document).ready(function(){
    $(".navbar").hide();
    $(function () {
        $(window).scroll(function () {
            if($(window).width() >= 768) { 
                if ($(this).scrollTop() > 500) {
                    $('.navbar').fadeIn();
                } else {
                    $('.navbar').fadeOut();
                }
            }
        });
    });
});
  }(jQuery));

Another approach is to use classes for adding and removing elements to prevent the flicker effect. However, this method may result in an abrupt transition, and I'm facing challenges with its implementation:

$(function() {
    var div = $(".navbar");
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 200) {
            div.removeClass('d-block').removeClass("d-md-none");
        } else {
            div.addClass("d-block").addClass('d-md-none');
        }
    });
});

Any assistance would be greatly appreciated. Thank you!

Answer №1

I managed to reproduce the blinking navbar on load. The issue lies in the .hide() function triggering when the document finishes loading. One potential solution is to set the navbar to be hidden initially through CSS.

To resolve this, you can simply add display:none to the navbar and remove the $(".navbar").hide(); line of code.

<nav class="navbar navbar-inverse" style="display:none;">
...
</nav>
<script>
(function ($) {
  $(document).ready(function(){
    // remove
    // $(".navbar").hide();
    $(function () {
        $(window).scroll(function () {
            if($(window).width() >= 768) { 
                if ($(this).scrollTop() > 500) {
                    $('.navbar').fadeIn();
                } else {
                    $('.navbar').fadeOut();
                }
            }
        });
    });
});
  }(jQuery));
</script>

Here is a working example: https://jsfiddle.net/oe5s6z0c/1/ I made some adjustments to include

<nav class="navbar navbar-inverse" style="position:fixed; display:none; width:100%;">
...
</nav>

Answer №2

By creatively combining JS and CSS media queries, I successfully achieved my desired outcome. The media queries ensure that the JS effects are only visible on desktop browsers, adding a smooth transition when adding or removing classes.

@media (max-width: 768px) {
  .navbar {
      opacity: 1!important;
    }
}

@media (min-width: 768px) {
  .navbar {
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.5s ease;
  }
}

(function ($) {
    $(document).ready(function(){
    // scroll functions
    $(window).scroll(function(e) {
        if($(window).width() >= 768) 

            var scroll = $(window).scrollTop();
            if (scroll >= 150) {
                $('.navbar').addClass("navbar-hide");
            } else {
                $('.navbar').removeClass("navbar-hide");
        }

    });

    });

})(jQuery); 

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

Attempting to achieve the effect where the entire row of a table changes color when the mouse hovers

I'm attempting to create a gradient effect for an entire row in a table when the mouse hovers over any cell within that row. Despite using what I believe is the correct CSS code, nothing changes upon mouseover (even though the original gradient appear ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Failed to set audio source to the source tag after receiving the ajax request

When making an ajax request to the database, I receive an audio link in response. The link is accurate in the variable but is not binding in the source tag. Below is the HTML code I am using to play the audio: function play(){ } < ...

Is there a way to add default text to a number input field that already has a value?

My current HTML input code is as follows: <input type="number" min="4" max="100" step="1" name="myInput" value="33"> The value of this input field is being populated from a cookie or storage that was set on a previous screen where the user provided ...

Add the "Class" attribute to the "td" element within the same column

I've been scouring the internet for hours, but I still can't crack this nut. <table> <tr> <th class="name">Name</th> <th class="age">Age</th> <th class="nick">Nick</th> </tr& ...

The `d-flex flex-column` is causing the image within the div to be hidden

The setup looks like this: <div className="d-flex flex-column"> <div> Text </div> <div style={{ backgroundImage: 'url(...)' }}> </div> </div> The URL is functioning correctly. The div element is ...

A guide on transferring data from JavaScript to HTML and efficiently directing it to a Laravel 5 controller

Recently, I have been exploring different ways to connect Javascript with HTML and interact with PHP. Although I am comfortable using plain PHP to send or retrieve data from a PHP backend, I decided to dive into Laravel5 as my PHP framework. So far, it has ...

Intermittent loading issues with Highcharts using AJAX requests

We've encountered intermittent errors when using Highcharts. Despite our efforts, we can't seem to pinpoint the cause of these issues in Chrome: Uncaught Highcharts error #16: www.highcharts.com/errors/16 VM210:16 HighCharts was already loaded V ...

The concept of variables within the jQuery each function

Can someone provide assistance? I want the variables id, zIndex, and width inside the function to be defined after jQuery.each is called, with their values coming from the array passed to the function MyFunction: console.log(id); //ID IS NOT DEFINED con ...

CSS Problem: The first-child, last-child, and only-child pseudo-classes are not functioning as expected when applied to lists

I am facing an issue with the following pseudo classes: first-child: The first a element within each div should have a red background. last-child: The last a element within each div should have a blue background. only-child: Only the a element of the last ...

jQuery Widget - Error: The method cannot be found in [object Object]

I am encountering an error when attempting to call my widget. Uncaught TypeError: Object [object Object] has no method 'koSpreadSheet' The plugin code: (function ($) { //Create spreadsheet app $.widget('koSpreadSheet', { ...

fixed divs that remain in place while scrolling

In the past, I have implemented a method similar to this: However, I am not a fan of the "flicker" effect that occurs when the page is scrolled and the div needs to move along with it. Recently, I have come across websites where certain elements (such as ...

Steps for implementing a select all feature with jQuery

I'm currently working on a jQuery function that is acting as a select-all option. Everything is functioning correctly except that when I deselect any of the child elements from select all, the option remains enabled. My goal is to enable or disable th ...

Tips on customizing the color of the arrow in an mdc-select dropdown menu?

I'm struggling to modify the default purple color of the dropdown arrow in an mdc-select: https://i.sstatic.net/DdDEv.png None of the sass mixins seem to be effective in making the change. Any suggestions on how this can be achieved? Here are my a ...

Submitting various ajax data from dynamically created fields

Is there a way to send multiple data from dynamically generated fields in ajax? I am facing an issue with using a for loop since I can't foresee the number of fields in advance. $.ajax({ type: 'GET', data:{ ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

Replace the icon in Material UI Stepper for steps that have errors

I am utilizing Material UI's Stepper component to display a checklist in this manner. The image below is from their documentation. https://i.sstatic.net/KfUos.png While attempting to add an error state to the checklist, I discovered a prop called er ...

Initiating an AJAX call to fetch JSON data

I am attempting to retrieve JSON data from https://twitter.com/i/search/timeline?f=realtime&q=blogger&src=typd Despite my efforts, I have encountered an error while making a cross-domain request: $(document).ready(function() { var contentType ...

Adjusting the sizes of images with varying aspect ratios to perfectly fit within a div without distorting its shape

I'm currently in the process of developing my portfolio website and I am faced with creating a simplistic image browser feature. My goal is to have a container div that adjusts in size according to the browser window, allowing it to house images of va ...

Generate an embedded iframe displaying a linked code snippet

I manage an online store and once a courier has been dispatched, I send out an email to customers with tracking information for their shipments. To streamline this process, I have implemented an input field (Code provided below). In this field, when a us ...