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

Finding the height of concealed content within a div using the overflow:hidden setup

I'm trying to create a div that expands when clicked to reveal its content. I've taken the following steps so far: Established a div with overflow:hidden property Developed a JavaScript function that switches between a "minimized" and "maximize ...

Executing AJAX on page load using jQueryHere is how you can initiate an AJAX

I have been utilizing jQuery to create an ajax call that occurs every x seconds. I am curious, is there a way to also trigger the same ajax function to run when the page loads? Below is the code snippet of my ajax function which currently triggers every 3 ...

Enhancing the synchronization of data between the model and the view in

Can AngularJS support "double data-binding" functionality? I am trying to extract mat.Discipline[0].nom_FR from an array containing nom_FR, nom_DE, nom_EN, and nom_IT. The value of mat.Langue[0].langue is either "FR", "DE", "EN", or "IT" based on the sel ...

Achieve a seamless transition for the AppBar to extend beyond the bounds of its container in Material

I am finalizing my app structure by enclosing it within an MUI Container with maxWidth set to false. The issue I'm facing is that the AppBar inside the container doesn't span the full width of the screen due to paddingX property enforced by the c ...

Troubleshooting HTML Output Display Issues

I've been trying to post my content exactly as I submit it, but for some reason, it's not working. When I enter two paragraphs in a post, the output doesn't maintain that formatting. Instead, it removes the paragraph breaks and displays the ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Finding the element and extracting its text value

Below is the HTML code: <span> <b>Order number:</b> </span> <span>A36HASJH</span> The value within the span element, A36HASJH, is dynamic and changes with each order. How can I identify this element and store it as a s ...

Analyzing JSON information and presenting findings within a table

Requesting user input to generate a JSON object based on their response. Interested in showcasing specific details from the object in a table format for user viewing. Questioning the efficiency and clarity of current approach. My current progress: In HTM ...

Code exists in the French language

My expertise does not lie in encodings... I am working on a website that incorporates various languages. The database is set to store content in UTF-8. Content retrieved from the database using jQuery and AJAX is not being displayed properly. For exampl ...

Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them. What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to ...

Tips for correctly adding a JSON output to a dropdown menu option

What is the correct way to add JSON results to a select option? Here is a sample of JSON data. AJAX code example: $.ajax({ url: 'sessions.php', type: 'post', datatype: 'json', data: { from: $ ...

Interactive image rotator featuring navigation buttons for next and previous slides

I recently followed a tutorial from W3Schools Now, I am looking to enhance it by adding previous / next buttons for the indicators, rather than for the slider itself Here is what I aim to accomplish: Below is the code snippet that I have been working on ...

Having Trouble With Your Font Display?

I am confident that my code is correct. Here's a snippet from what I've done: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="homepage.css"/> </head> <body> <div id="menu"> &l ...

Retrieve the data stored within the html.Append() method

I'm encountering an issue with the following code in C# Code Behind for my ASPX file. I am unsure of how to retrieve the value. Code Behind: html.Append("<input type='radio' name='radioButton' id='radioButton' runat ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Moving data of a row from one table to another in Laravel by triggering a button click

For instance, consider a scenario where clicking a button moves a row to another table in the database and then deletes it. Implementing this functionality in Laravel seems challenging as I am unable to find any relevant resources or guidance on how to pro ...

Unable to deactivate account, experiencing technical issues

After running once, the code in deactivate_myaccount.php throws an error stating: "Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\includes\includes\header-inc.php on line 2". Furthermore, t ...

Unleashed placement and drifting

Is it possible to style this layout without specifying an exact height for "Element 1"? Code Element1 { positon: relative; width: 100%; height: auto; /* Avoiding specific height */ } Inner1 { position: absolute; top: xyz px; left: xyz px; } Inner2 { po ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...