Restoring a navigation bar to its original state once scrolling back to the top of the page

Currently, I am expanding my knowledge of javascript and jQuery. While working on a project website, I decided to enhance the navigation by making it smaller and transparent as users scroll through the page. This is the code snippet that I implemented:

$(document).scroll(function(){
  $('.nav').css({"opacity": "0.85", "height": "55px"});
  $('.nav-container').css({"margin-top": "-13px", "font-size": "1.4em"})
});

However, I would like the navigation to return to its original state once the user scrolls back to the top of the page. It seems that there isn't a specific jQuery event for this requirement.

Answer №1

Here is a custom solution that I recommend:

$(document).scroll(function () {
    // targeting the necessary elements:
    $('#nav, .nav-container')[
        // checking if the window is at the top and applying 'removeClass' or 'addClass' accordingly:
        $(window).scrollTop() == 0 ? 'removeClass' : 'addClass'
    ]('scrolled');
});

Apply the following CSS styles:

.nav.scrolled {
    opacity: 0.85;
    height: 55px;
}

.nav-container.scrolled {
    margin-top: -13px;
    font-size: 1.4em;
}

Check out the JS Fiddle demo here.

This method also ensures valid HTML usage.

Source material for further reading:

Answer №2

Here is the updated jsfiddle code link

The modification was made to the .scroll() function:

$(document).scroll(function () {
var scroll = $(this).scrollTop();
    if(scroll > 0){
        $('.menu').addClass('scrolled');
        $('.menu-bar').addClass('scrolled');
    } else if(scroll == 0){
        $('.menu').removeClass('scrolled');
        $('.menu-bar').removeClass('scrolled');
    }
});

In addition, the following css was included:

.menu.scrolled {
    opacity:0.85;
    height:55px;
}

.menu-bar.scrolled {
    margin-top:-13px;
    font-size:1.4em;
}

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

Added the .active state to the menu navigation successfully, however the active color was not implemented

My primary navigation menu is managed by WordPress and can be seen below. I aimed to modify the active state when a user clicks on a link in the menu by adding background-color and color for styling purposes. Although changing the background-color upon cl ...

Passing a message from a Struts2 action to jQuery

When using jQuery Ajax to call a Struts2 action, I have the following setup: $.ajax ({ url: 'callAction.action', type: 'POST', data: data, dataType: 'string', success: function (data ...

Problem with child divs escaping outside the boundaries of the parent div

I'm encountering an issue with my HTML/CSS code. I have a parent div called "secClass" which contains two child divs - secClass1 and secClass2. The problem is that the content within the child divs is not staying contained within the parent div. Can y ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...

"Encountered an undefined error with the title property of this.state.project in the Wordpress API

I'm currently working on a project that involves a Backend Wordpress and a front-end React setup. However, I've encountered an issue when attempting to retrieve the title.rendered from the JSON Data. This error is displayed: TypeError: this.sta ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

The jQuery serialize function encounters issues when used with Ajax in IE9

function getTime(){ var timestamp = new Date(); return timestamp.getTime(); } function displayValues() { var values = ($("#this").serialize()); $("#results").text(values); } $(":checkbox, :radio").click(displayValues); ...

having difficulty in transmitting json data using ajax

Struggling to send JSON data to my PHP script via AJAX and it keeps returning NULL as a response. The jQuery script I'm using involves creating a JSON data on a click event and then attempting to send it to the PHP script. Here's a snippet of the ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

Increase the Step Size of an HTML Number Input by Holding Down the Time

Is there a way to implement increasing increment/step size for number inputs in HTML based on how long the user holds the stepper arrows? For instance, starting at step size=1 and gradually ramping up to larger increments like 5, 10, 20, etc. after holdin ...

Resolving the problem of JQXdropdown in PHP

Currently, I am utilizing jqxdropdownlist.js to create a dropdown feature in my PHP project. The main requirement is that upon changing the selection, I need to redirect users to specific pages. However, I encountered an issue with the functionality. Let& ...

Ways to pass Angular variables to JavaScript while utilizing the $scope() function

This is my process for receiving input: extracting data from an sql table, passing it through php slim, integrating it into angularjs, and displaying it on a website. I am looking to retrieve a variable in javascript that has been passed from php slim to ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Displaying Response After Making an Ajax Request

How can I display the results of an echo from action.php back on index.php while executing the script in AJAX? For example, index.php calls action.php (AJAX) and once it is successful, action.php will echo some text. How do I display this text on index.ph ...

Using PHP and JQuery to send two variables via the post method

I've been attempting to send two variables from two input fields using jQuery to a PHP page, but I'm having trouble retrieving the data. It seems to work fine when I only have one variable, but as soon as I try with two, it doesn't seem to w ...

There was an error in the search: [parse_exception] The search source could not be parsed. A field name was expected, but instead [

I'm experiencing a query parsing exception while utilizing JavaScript for Elasticsearch configuration found in elastic.js file. Results are obtained when the filtered part is removed. However, upon adding it back, an exception occurs. var client = r ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

Setting up TailwindCSS in Nuxt3: A step-by-step guide

Looking to customize the default font Proxima Nova from TailwindCSS in my Nuxt3 project but navigating the file structure is a bit tricky for me. I've gone ahead and installed the tailwindcss module: npm i -D @nuxtjs/tailwindcss and added the module ...