Make sure the navigation bar is fixed to the top of the page only

Looking for a solution to stick the navigation menu to the top of the screen only when the screen is wider than 782px.

Progress so far: https://jsfiddle.net/ah4ta7xc/1/

Encountering an issue where there is an unintended gap at the top when applying the sticky-menu class.

HTML:

<div id="foo">Logo and other content</div>
<div id="main-menu">Main Site Menu</div>

CSS:

body {
    height: 3000px;
}

#foo {
    height: 50px;
    background-color: #ccc;
}

#main-menu {
    width: 100%; 
    height: 30px; 
    background-color: black;
    color: white;
    text-align: center;
    padding: 10px;
}

.sticky-menu {
    z-index: 10;
    width: 100%;
    position: fixed;
}

jQuery:

$(function(){
    if ($(window).width() > 782) {
        $('#main-menu').addClass('sticky-menu');
    }

    $(window).resize(function () {
        if ($(window).width() > 782) {
            $('#main-menu').addClass('sticky-menu');
        }
        else {
            $('#main-menu').removeClass('sticky-menu');
        }
    });  
});

Answer №1

To maintain a clean stylesheet for the body, consider incorporating the following CSS lines:

margin: 0;
padding: 0;

Answer №2

To implement a sticky navigation bar that activates when the user scrolls to a certain point, you can use the following JavaScript code:

$(window).scroll(function () {
     var scroll = $(this).scrollTop();
     var topDist = $('#main-menu').offset().top;

     if (scroll > topDist) {
         $('#main-menu').addClass('sticky-menu');
     } else {
         $('#main-menu').removeClass('sticky-menu');
     }
});

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

Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1. Within a div element, I have two TextInput fields. const ...

Putting off the jQuery UI autocomplete focus event

Currently, I am utilizing an autocomplete feature from version 1.8.23 of the jQuery UI library. Here is a snippet of my code: $(this).autocomplete({ autoFocus: true, minLength: 2, delay: 100, source: function(request, response) ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

A method for setting values independently of [(ngModel)] within an *ngFor loop and selecting an HTML tag

I am encountering an issue with [(ngModel)], as it is syncing all my selections to the same variable. My variable is selectStations = []; Therefore, when I choose an option in one select element, it updates all select elements to have the same selected o ...

Creating characters dynamically based on the length of user input in VSCode Snippet

Here is a simple vue-html snippet: { "BANNER1": { "prefix": "banner", "body": ["<!-- ----------------", "/// $1", "--------------------- -->"] } } This sni ...

What is the best way to connect my choices to a dropdown menu when utilizing bindingHandlers in knockoutJS?

I am having trouble populating options in a dropdown menu <select data-bind="options: $root.SomeArray, selectedOptions: cities, optionsText: 'LocDescription', selectPicker: {}"></select> ko.bindingHandlers.options = { init: funct ...

Ways to ensure that the height of a div remains consistent across all scenarios

Below is the code snippet, which utilizes bootstrap. I need to set a fixed height for a div that is populated dynamically from a database. The goal is to maintain the height of the div regardless of the content length. If the book title and description e ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

Attempting to alter the appearance of my validation control by implementing a custom style sheet theme

After naming a style sheet theme Basic and applying it to my web.config file, I created a Validator class in the css file. Utilizing the cssClass attribute with the Validator type, I successfully adjusted the font-weight property but struggled to change th ...

Creating an HTML table from dynamic JSON data - A comprehensive guide

I am in need of a solution to transform JSON data into an HTML table format quickly and easily. Can anyone provide guidance on effectively utilizing PartialView to recursively render tables, ensuring that most details are visible? ...

Ways to eliminate extra space from the edges of a container

Trying to wrap my page in a Material UI container component, but there's this persistent whitespace on the outside that no matter how much I tweak the margin and padding, it just won't disappear. Any CSS wizard out there with a workaround to make ...

Adjusting page layout following window dimension changes

Every time I work on developing HTML pages, I encounter issues with window resizing. The alignment of the page gets disrupted and elements end up overlapping each other. I want my page to maintain its layout when resized, with scrollbars appearing instea ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

Displaying image titles when the source image cannot be located with the help of JavaScript or jQuery

I am currently facing an issue where I need to display the image title when the image is broken or cannot be found in the specified path. At the moment, I only have the options to either hide the image completely or replace it with a default image. $(&apo ...

I'm confused as to why the icon color isn't changing on the Blogger homepage for each individual user

I'm experimenting with changing the eye color based on visitor count. It works perfectly fine on static posts in my Blogger, but it fails to update the eye color properly on my homepage according to the set numeric values. Instead of displaying differ ...

Learn the process of dynamically adding new rows and assigning a distinct ng-model to each row

Does anyone know how to create a dynamic table in HTML with unique ng-models for each cell? I've tried the following code, but I'm struggling to figure out how to add ng-model. <!DOCTYPE html> <html> <head> <style> table, ...

Why do CSS Variables have different syntax for setting and getting values?

When we use CSS Variables, also known as CSS Custom Properties, the syntax for setting and getting values is different. To set a value for --my-custom-width, we use: :root { --my-custom-width: 120px; } Similarly, to get the value of --my-custom-width, ...