Troubleshooting: jQuery fixed header glitch with slide down effect

I am new to jQuery and seeking help without harsh judgment. My goal is to make the header fixed when scrolling down 300px on the page, and remove the fixed position if less than 300px. Additionally, I would like to animate the header by sliding it down when scrolling down and back up when scrolling to the top. A good reference for what I want can be found on this site.

Here is my HTML structure:

<div class="heading-wrapper">
<a href="#">1 </a>
<a href="#">2</a>
<a href="#">3</a>
<a href="#">4</a>
<a href="#">5</a>    
</div>

Corresponding CSS:

.heading-wrapper {
    width: 100%;
    height: 65px;
    background: #000;
    position: relative;
}

.heading-wrapper.fixed {
    position: fixed;
    top: -80px;
    left: 0;
    right: 0;
}

And the jQuery script:

$(window).scroll(function() {
    if ($(this).scrollTop() > 300){  
        $('.heading-wrapper').addClass("fixed");
        $('.heading-wrapper.fixed').animate({'top' : '0px'}, 800);
    }
    else{
        $('.heading-wrapper.fixed').animate({'top' : '-80px'}, 800);
        setTimeout(function(){
            $('.heading-wrapper').removeClass("fixed");
        },800); 
    }
});

However, the current implementation does not behave as desired. Some issues include:

  1. No animation when scrolling with the mouse wheel
  2. Animation only occurs once
  3. The slide-up animation never triggers
  4. Rapid scrolling breaks the structure and styling

I kindly ask for assistance in resolving these problems. Please be patient and understanding while helping me improve this functionality! :)

For a visual representation of the issue, visit this JsFiddle link.

Answer №1

Check out the demo here

JavaScript code:

$(document).ready(function () {
    $("header").before($("header").clone().addClass("animateIt"));
    $(window).on("scroll", function () {
        $("body").toggleClass("down", ($(window).scrollTop() > 100));
    });
});

CSS styling:

body, html {
    margin:0;
    padding:0;
}
header {
    position: relative;
    width: 100%;
    height: 60px;
    line-height: 60px;
    background: #000;
    color: #fff;
}
header.animateIt {
    position:fixed;
    top:-60px;
    left: 0;
    right: 0;
    z-index:999;
    transition:0.4s top cubic-bezier(.3, .73, .3, .74);
}
body.down header.animateIt {
    top:0;
}
.content {
    padding: 0 20px 20px;
    background: #fff;
    line-height: 1.5;
    color: #333;
}

HTML structure:

<header>
    <a href="#">1 </a>
    <a href="#"> 2</a>
    <a href="#"> 3</a>
    <a href="#">4</a>
    <a href="#">5</a>    
</header>

Answer №2

My approach to this task would be like so:

To start, consider the specific browsers you need to support and include the following CSS code:

.header-container {
   position: fixed;
   top: -80px;
   transition: top 1s linear; /*adjust as needed*/
   [...]
}

.header-container.relative {
    position: absolute;
    top: 0px;
}

.header-container:not(.relative).fixed {
    top: 0px;
}

Next, in JavaScript :

var $container = $(".header-container");
var $window = $(window);
var doc = document.documentElement, body = document.body;
var scrollTop = 0;

$container.clone().appendTo("body").addClass("relative");

$window.scroll(function () {
   scrollTop = (doc && doc.scrollTop || body && body.scrollTop || 0);
   if( scrollTop > 300)
       setTimeout(function(){$container.addClass("fixed");},0);
   else if( $container.hasClass("fixed") )
      setTimeout(function(){$container.removeClass("fixed");},0);
});

I have made adjustments to your JSFiddle example.

UPDATE : Added a cloned menu with absolute positioning.

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

Guide on importing a custom CSS file from Syncfusion Theme Studio into an Angular project

Is there a way to incorporate custom scss files downloaded from Syncfusion Theme Studio into Angular CLI without adding the URL to the styles section in angular.json? Can we directly import it into styles.scss instead? I attempted to do so by including th ...

Trouble initializing jSignature on multiple pages with jQuery Mobile

My jquery mobile app is displaying 3 jsignature divs correctly on certain pages, but not on others. The problem arises when the div shows up with a squished height and is unresponsive to touch: Currently, I'm loading these divs using a document ready ...

Using jQuery to smoothly animate scrolling to the top of a

How can I create a "scroll to top" button at the bottom of my page that smoothly scrolls to the top? Despite using an "animate({scrollTop})" script, the scroll animation is not working and it jumps directly to the top. This is the script I am using: $(&a ...

How can I use a button to programmatically activate the update callback function of a sortable widget?

In the example provided in this jsbin, there is a sortable list and a button. When the button is clicked, something is added to the sortable list. The goal is to determine which event of the sortable list is fired (update or receive) and then perform a spe ...

Angular 5 combined with Electron to create a dynamic user interface with a generated Table

I am working on an Angular Pipe: import {Pipe, PipeTransform} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import * as Remarkable from 'remarkable'; import * as toc from 'markdown-toc&a ...

Is there a way in Selenium to determine the type of tag associated with the element we are trying to locate?

Is there a way in Selenium to determine the type of tag? On my automation page, some fields may change their type. For example, if the first field value is greater, the second field becomes an input text; if the first is "IN", then a dropdown appears. So, ...

What is the best way to display several markers on a Google Map at once?

I am currently working on a functionality where I retrieve latitude and longitude from a JSON file and display markers on a Google map. However, my issue is that only one marker is appearing on the Google map, while the others are not showing up. Below i ...

Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag: $(document).ready(function(){ var FamilyTree = function() { }; FamilyTree.prototype.displayMessage=function() { alert("test"); } }); Then, within the bo ...

What is preventing jQuery 3 from recognizing the '#' symbol in an attribute selector?

After updating my application to jQuery 3, I encountered an issue during testing. Everything seemed to be working fine until I reached a section of my code that used a '#' symbol in a selector. The jQuery snippet causing the problem looks like th ...

Using ASP.Net web forms with Bing Map AutoSuggest API

Currently, I am integrating the Bing Map API into a web forms application for address lookup functionality. I attempted to follow this method, which worked seamlessly in an HTML form. However, when I tried implementing it in an ASP.NET Web Form (with the ...

When errors occur while printing HTML through an Ajax request, it can hinder the functionality of other JavaScript code

I recently conducted an interesting experiment on my website. The concept involved sending an AJAX request to a PHP file, which then retrieved a random website by using various random words for search queries on Google. The retrieved website content was th ...

How can JavaScript be used to parse an XML file? Should we consider using SAX for handling large XML files

Hello everyone, I am feeling very frustrated and overwhelmed with my current situation. I have been searching everywhere for a solution but seem to be going in circles. This will be my first attempt at working with xml and it's quite daunting, espec ...

Reposition the jQuery tooltip arrow

I need help adjusting the position of the arrow to the left near the text box. Can anyone assist with this? Here's what I've tried so far: Check out the working example here: http://jsfiddle.net/b8fcg/ HTML: <input id="test" title="We ask ...

Attempting to successfully transfer data with more than 524288 bytes using the Text input type and ToDataURL

Currently, I am facing an issue while trying to generate an image using DataURL of a Canvas in JavaScript. Upon hitting the submit button, the value is sent to a text input tag (<input type='text'>). However, on Chrome, it seems that the te ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

Obtain the URL for the JavaScript code that is currently running

Can anyone help me find the URL of the JavaScript currently being executed? I am aware of using window.location.href for the current page, but that doesn't necessarily provide the path to the script that is running. Any assistance would be greatly ap ...

Executing Python script via AJAX or jQuery

I need to execute Python scripts from JavaScript. The goal is to provide an input String to the Python script as an argument and then showcase the output on our webpage. Below is the Python code that runs smoothly on my Linux box: ./sample.py 12345 produc ...

Implementing personalized validation post-control initialization in an Angular 4 reactive form

I have been working on an Angular 4 application and using reactive forms. For one of my forms, I am trying to implement custom validation on a control after it has been initialized, based on whether a checkbox is checked or unchecked. CODE form.componen ...

What is the amount of memory consumed by a string data type?

Just a quick query - how much data (in bytes) do strings occupy? Does each character in a string take up one byte? I attempted to look it up, but unfortunately ws schools didn't provide an answer... I'm curious about this as I'm looking to ...

Tips for locating the index of a substring within a string with varying line endings using Typescript

I am faced with the task of comparing two strings together. abc\r\ndef c\nde My goal is to determine the index of string 2 within string 1. Using the indexOf() method is not an option due to different line endings, so I require an altern ...