Toggle the class to slide in or out of the div

I am attempting to create a header with two positions - one absolute and one fixed. I want the header to smoothly slide in as you scroll down, and then slide out when you scroll back to the top. However, I am having trouble getting it to slide; instead, it just appears and disappears abruptly while scrolling.

(function($) {          
    $(document).ready(function(){                    
        $(window).scroll(function(){                          

            if ($(this).scrollTop() > 300) {
   $('.header').addClass('fixed');
           } else { 
$('.header').removeClass('fixed');
            }
        });
    });
})(jQuery);
.header { 
  position: absolute;
  width:100%; 
  height:86px;  
  background:  red;
  color: #fff;
}
.header.fixed { 
  width:100%; 
  height:66px; 
  position:fixed;
  top:0px;
  background:#000;
  color: #fff;
  -moz-transform: translateY(-130px);
  -ms-transform: translateY(-130px);
  -webkit-transform: translateY(-130px);
   transform: translateY(-130px);
   transition: transform .5s ease;
}
.header.fixed {
    -moz-transform: translateY(0);
    -ms-transform: translateY(0);
    -webkit-transform: translateY(0);
    transform: translateY(0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="header">
  <span>My Div</span>
  </div>
  <div style="height: 2000px; background-color: grey;">Content</div>

Answer №1

Instead of using width: 100%, it is recommended to use left: 0, right: 0 for absolute elements to achieve 100% width.

To update your styles on .fixed, modify them as follows:

.header.fixed {
  position: fixed;
  left: 0;
  right: 0;
  height:66px;
  background:#000;
  color: #fff;
  animation: headerSlideIn 0.5s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
} 

@keyframes headerSlideIn {
  0% {
    top:-66px;
  }

  100% {
    top: 0;
  }
}

By implementing these changes, you should see the desired outcome. If you are experiencing jittery behavior on mobile due to the top property, consider replacing it with transform: translateY() and set top: 0.

The reason the previous code was ineffective is because:

.header.fixed {
    -moz-transform: translateY(0);
    -ms-transform: translateY(0);
    -webkit-transform: translateY(0);
    transform: translateY(0);
}

I hope this explanation clarifies things.

(function($) {          
    $(document).ready(function(){                    
        $(window).scroll(function(){
            if ($(this).scrollTop() > 300)
            {
              $('.header').removeClass('slide-back');
       $('.header').addClass('fixed');
          }
            else if ($(this).scrollTop() == 0)
            {
      $('.header').removeClass('fixed');
            }
        });
    });
})(jQuery);
.header { 
  position: absolute;
  left: 0;
  right: 0;
  height:86px;
  background:  red;
  color: #fff;
  transition: all 0.5s ease;
}

.header.fixed {
  position: fixed;
  height: 66px;
  background: #000;
  color: #fff;
  animation: headerSlideIn 0.5s ease;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

@keyframes headerSlideIn {
  0% {
    top:-66px;
  }
  
  100% {
    top: 0;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="header">
  <span>My Div</span>
  </div>
  <div style="height: 2000px; background-color: grey;">Content</div>

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

Sort through the JSON data and showcase it in a gridded format

I need assistance with displaying data from a JSON object in a grid based on user selections. The user should be able to select a year and make from a dropdown menu, and the corresponding data should then be filtered and displayed in a grid. For example, i ...

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

What is the best way to horizontally align Font Awesome icons in the center?

In my table, I have a Font Awesome icon that I'm trying to align left with text and center the icons. I attempted to center the <i> element but it didn't work as expected: Here is the HTML code: <td><i class="icon-ok"></i&g ...

Codeigniter - Ajax request successful in remote server but fails in local server

I am encountering an issue with my web application that makes Ajax requests to a server using Codeigniter-php code. While the Ajax requests work fine on the local server, they do not function properly when the application is hosted on a remote server. The ...

Tips on retrieving values from input files using jQuery

Is there a way to retrieve the value of an input type using jQuery? Specifically, when I add a file to the input file, I want to dynamically add more input types with the file's value. Currently, I am using the following code: $('#show_input&apo ...

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

Having trouble with the JQuery Ajax POST method? Maybe try using $.post instead

As a coding novice, I attempted to create a jQuery Ajax program that displays the ID and password entered by the client. However, I'm facing issues with getting it to work as intended. I've gone over the code multiple times <fieldset> & ...

If the element contains a specific class, then replace the text within the element with a new set of words

Looking for a solution: <form id="new_user"> <div id="first-name"> <label for="user_profile_attributes_first_name"><abbr title="required">*</abbr> First name</label> </div> </form> I need to change the text ...

Guide on displaying the <html> tag within text using AngularJS

I need to display some data in HTML, which looks like this: <p>abcd efg hijk....(<a href=\"http:\/\/www.facebook.com\/stock\/NBR\">NYSE:NBR<\/a>),, however, there are some HTML tags within ...

Dividing a string into an array and displaying it in a table using Laravel

Retrieving a string from the database and using the explode function to split the values. Below is the code snippet: $data = DoctorRegistration::select('products') ->where('doctorid','=',$doctorid) ->get(); ...

Transfer your documents effortlessly as soon as they are

I am having trouble implementing an automatic file upload feature without the need for a separate upload button. Below is the code I have so far, excluding the irrelevant CSS. //html <!-- some codes here--> <input type="file" id="f ...

What is the best way to incorporate a loading icon onto a webpage that exclusively runs JavaScript functions?

I frequently use Ajax load icons to indicate progress during ajax requests. Is there a way to achieve the same result using regular JavaScript? For instance: $('button').on('click', function(){ showLoadingIcon(); lengthyProces ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

IE page refresh causing jQuery blur to malfunction

Our website features a textbox with a watermark that appears and disappears based on focus and blur events in jQuery. However, we have encountered a unique issue with Internet Explorer browsers. Whenever a user clicks on the textbox, the watermark disapp ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...

There is a missing template at the specified location: index.html in Django

Hello, I recently created a new project and placed the index.html file in the templates directory. However, when I run the server, I encountered an error message stating TemplateDoesNotExist at /. Can anyone point out what mistake I might have made? Below ...

I'm looking for a way to implement pagination using Jquery AJAX in my PHP application. How

Currently, I am implementing pagination for my MySQL data using PHP. My aim is to utilize the jQuery load function in order to dynamically load the next page when a pagination link is clicked. The pagination links are structured as follows: <div class= ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...