turn off the static to fixed navbar script for mobile devices

I've been experimenting with a navigation bar/header design for my website. I have it set up so that when you scroll 100px past the logo, the navbar becomes fixed at the top of the page.

Everything seems fine with this setup, but on smaller screens, I would like to keep the navbar fixed at the top as well since the logo is hidden. The issue arises when scrolling down on these smaller viewports, causing the script to hide and then reveal the navbar unnecessarily. I tried adding some CSS to prevent this on screens with a max-width of 768px, but it didn't work as expected. Is there a better way to handle this situation?

Feel free to check out the jsfiddle link in mobile view and try scrolling down.

Below is the code snippet I'm currently using:

$(window).scroll(function() {
    var nav = $('#custom-bootstrap-menu');
    var body = $('body');
    var top = 100;
    var logo = $('div#navlogo');
    if ($(window).scrollTop() >= top) {

        nav.addClass('navbar-fixed-top');
        body.addClass('padding-fifty');
        logo.css('display', 'block');

    } else {
        nav.removeClass('navbar-fixed-top');
        body.removeClass('padding-fifty');
        logo.css('display', 'none');

    }
});

Appreciate any advice or suggestions you may have!

Answer №1

Update: Tweaked the fiddle. What do you think now?

This technique involves duplicating a navigation bar for mobile display, visible only on small screens while hiding the original navigation bar.

https://jsfiddle.net/6gyc6aeq/

JavaScript

$(window).scroll(function() {
var nav = $('#custom-bootstrap-menu');
var body = $('body');
var top = 100;
var logo = $('div#navlogo');
if ($(window).scrollTop() >= top) {

    nav.addClass('navbar-fixed-top');
    body.addClass('padding-fifty');


} else {
    nav.removeClass('navbar-fixed-top');
    body.removeClass('padding-fifty');


}
});

$("#mobile-only").html($("#custom-bootstrap-menu").html());

HTML

<body>

<div id="logo">
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <h1>CHEEZ-IT</h1>
        </div>
        <div class="col-md-6">

        </div>
    </div>
  </div>
</div>    

<!-- Static navbar -->
<nav id="custom-bootstrap-menu" class="navbar navbar-default navbar-static-top">
   ...
 <nav id="mobile-only" class="navbar navbar-default navbar-fixed-top">

 </nav>


<div class="container">
<div class="row">
    <div class="col-md-12">
       ...
  </div>
</div>

CSS

#logo {
height: 100px;
}

.padding-fifty {
  padding-top: 50px;
}
...
@media only screen and (max-width: 768px) {
  ...
 }

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

What steps can I take to ensure that the div doesn't overlap with the scrollbar while still maintaining the functionality of my JQuery ScrollTo plug-in?

Currently troubleshooting an issue with a website I'm constructing. Utilizing the jQuery plug-in "scroll to" for a single-page layout with multiple sections, I am aiming to keep the navigation bar fixed at the top of the page while allowing users to s ...

Steps to activate ng-pattern exclusively when the field has been interacted with:

I've encountered a challenge with an input box that has an ng-pattern for link validation. Our project manager has requested that the text 'http://' be pre-filled in the input field, but doing so breaks the ng-pattern validation and prevents ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

Tips for aligning an element at the center based on the viewport rather than the parent element

I'm trying to center an element within a header with five elements, consisting of a button on the left, a logo in the middle, and three buttons on the right. I want the logo to be centered based on the viewport. I've created a codepen to demonstr ...

Tips for modifying the input variables of the createControls function in JavaScript

I encountered an issue while working with a function createControls(){ return new THREE.TrackballControls( camera,domElement );} that was created using THREE.TrackballControls=function(object, domElement){.....} controls = createControls(camera, rende ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Understanding how to access both 'this' variables in TypeScript

When working in TypeScript, it's important to note that defining a function using () => {...} will make the this variable refer to the instance of the surrounding class. Conversely, using function () {...} will result in the this variable maintaini ...

What causes the presence of undefined elements within the ngOnInit function of Angular?

When I initialize a library in my ngOnInit method like this: ngOnInit() { this.$grid = jQuery('.grid').masonry({ // options itemSelector: '.grid-item',//, columnWidth: 384, gutter: 24 }); ...... } and then call the method from ...

Creating specialized error messages for jquery's ajax() function

In my custom httphandler (.ashx) file, I have a method called Foo which throws an exception and handles it by serializing it into an AjaxError object. private void Foo() { try { throw new Exception("blah"); } catch(Exception e) ...

Angular does not assign the ng-invalid-class to the input

In order to register custom validation methods for custom form elements, we use extra directives as shown below: <ng-form name="validatorTestForm"> <our-input-directive name="validatorTest" ng-model="ourModel"/> ...

Integrating Cache and Resolved Promises in Angular's UI-Router: A Comprehensive Guide

I have been working on an Angular app where I used to load all data before displaying any page through the ui-router resolve. However, I found that some data was being repeated, so I decided to cache the data using localStorage. Now I'm trying to figu ...

Difficulty encountered in positioning a div element

I have been attempting to align the div with class bioDiv under the image, but despite various attempts, I find myself feeling more and more confused. Can someone please review the code for me and offer a clue? I want to retain the same appearance, just re ...

Parsing JSON data to extract values stored in a two-dimensional array

In order to develop a basic version of Tic Tac Toe, I decided to store game data in a JSON file. Here is an example of how the file is structured: [ { "turn": "x", "board": [ [ " ...

How to generate a dropdown menu with hyperlinks in a Rails application

I am trying to set up a dropdown menu with clickable links as options, but I am having trouble finding an easy solution. Can anyone provide a simple example of how this can be achieved? Thank you ...

Extract user's location using JavaScript and transfer it to PHP

My goal is to utilize JavaScript to retrieve the latitude and longitude, then compare it with the previous location, similar to how Facebook authenticates logins from different devices. To accomplish this, I have implemented 2 hidden fields which will capt ...

Can Helmet Package in Node.js with React.js Provide Frontend Security?

I'm seeking advice on how to ensure the security of my frontend when using Node.js as a backend. Specifically, I've built my website entirely with React for the frontend and utilized Axios to communicate with my Node.js backend for data retrieval ...

Why does my vanilla JavaScript function work on JsFiddle but not on my website?

Having a strange issue here. I've created a function that functions perfectly on jsFiddle, but when implemented in my HTML file, it doesn't seem to work... var el = document.querySelectorAll(".sp-methods li:first-child"); for (i = 0; i < el.l ...

Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box. <!-- HTML code for changing zip c ...

Instructions for utilizing float:left and list-style-type within HTML are as follows: I am currently experiencing issues with implementing the float:left and list-style-type properties in my code

I'm attempting to align a button list to the left using the float: left property and also remove list styles, but for some reason it's not working as expected. //CSS #tus{margin:5px;padding:0;width:640px;height:auto;} #tus ul{margin:0px;padding: ...

Fix alignment issue with Bootstrap tabs when resizing

I've been using Bootstrap to create a tabs section and it's looking great thanks to the "nav-justified" class. However, I noticed that when I shrink the tab size, the Global Indices Tab, which is slightly larger than the other tabs, moves onto th ...