Is there a way to trigger a CSS3 animation to play when scrolling down and then play in reverse when scrolling up?

Using a blogger website, I have successfully set up sticky navigation. However, when scrolling back up, the navigation bar pops back into place without any animation. I am looking for a solution to smoothly return the navigation bar to its original position and size. You can see the issue on my test blog. The animation works when scrolling down but not when scrolling up.

I cannot create a JSFiddle for this as the template I'm using is complex. But I believe adding a Javascript code could fix the problem. It would need to be integrated into the existing code that activates the sticky navigation.

Below is the CSS used for the fixed navigation bar as well as a property to reverse the animation. I just need help implementing it correctly in the Javascript code.

sticknav {
    background: #b50000;
    height: 46px;
    width: 1080px;
    margin-right: 0px;
    margin-left: 413px;
    left: 0px;
    right: 0px;
    position: relative;
    z-index: 1;
    border-top: 4px solid #e50000;
    webkit-box-shadow: 0 2px 6px rgba(0,0,0,0.49);
    box-shadow: 0 2px 6px rgba(0,0,0,0.49);
}

.fixed {
    position:fixed;
    animation: fill 333ms forwards ease-in-out;
    -webkit-animation: fill 333ms forwards ease-in-out;
}
@keyframes fill {
    from {margin-left: 413px; width: 1080px;}
    to {margin-left: 0px; width: 100%;}
}
@-webkit-keyframes fill {
    from {margin-left: 413px; width: 1080px;}
    to {margin-left: 0px; width: 100%;}
}
.unfixed {
    position:fixed;
    animation: unfill 333ms forwards ease-in-out;
    -webkit-animation: unfill 333ms ease-in-out;
}
@keyframes unfill {
    from {margin-left: 0px; width: 100%;}
    to {margin-left: 413px; width: 1080px;}
}
@-webkit-keyframes unfill {
    from {margin-left: 0px; width: 100%;}
    to {margin-left: 413px; width: 1080px;}
}

Here is the Javascript code:

$(document).ready(function() {
  var aboveHeight = 205;

  $(window).scroll(function(){
    if ($(window).scrollTop() > aboveHeight){
      $('sticknav').addClass('fixed').css('top','0').next().css('padding-top','60px');
    } else {
      $('sticknav').removeClass('fixed').next().css('padding-top','0');
    }
  });
});

A slightly modified version of the code partially works. When scrolling, the bar gets fixed to the top, expands at 205 pixels down, and retracts when scrolling back up. However, it remains fixed in place. I want it to return to its original position after retracting.

$(document).ready(function() {

var aboveHeight = 205;

    $(window).scroll(function(){
        if ($(window).scrollTop() > aboveHeight){
        $('sticknav').addClass('fixed').css('top','0').next().css('padding-top','60px');
        } else {
       $('sticknav').removeClass('fixed').next().css('padding-top','0');
        }
    });
    $(window).scroll(function(){
        if ($(window).scrollTop() < aboveHeight){
        $('sticknav').addClass('unfixed').css('top','0').next().css('padding-top','60px');
        } else {
       $('sticknav').removeClass('unfixed').next().css('padding-top','0');
        }
    });
});

Answer №1

To improve the scrolling functionality, it's advisable to consider an additional condition for when the scroll is below a certain height:

$(document).ready(function() {
  var aboveHeight = 205;
  $('.sticknav').addClass('unfixed');

  $(window).scroll(function(){
    if ($(window).scrollTop() > aboveHeight &&  $('.sticknav').hasClass('unfixed')){
      $('.sticknav').addClass('fixed').removeClass('unfixed').css('top','0').next().css('padding-top','60px');
    } else if($(window).scrollTop() < aboveHeight  &&  $('.sticknav').hasClass('fixed')){
      $('.sticknav').addClass('unfixed').removeClass('fixed').next().css('padding-top','0');
    }
  });
});

Additionally, consider moving the CSS styles for 'top' and padding to a separate css file.

Answer №2

Give this a shot

navbar {
    background: #b50000;
    height: 46px;
    width: 1080px;
    margin:auto;
    left: 0px;
    right: 0px;
    position: absolute;
    z-index: 1;
    border-top: 4px solid #e50000;
    webkit-box-shadow: 0 2px 6px rgba(0,0,0,0.49);
    box-shadow: 0 2px 6px rgba(0,0,0,0.49);

    -webkit-transition: all 1s;
       -moz-transition: all 1s;
        -ms-transition: all 1s;
         -o-transition: all 1s;
            transition: all 1s;

}
.fixed-nav {
    position: fixed;
    width: 1200px;
}

$(window).scroll(function(){
  if ( $(window).scrollTop() >= 205){
      $('navbar').addClass('fixed-nav').css('top','0').next().css('padding-top','60px');
  } else {
      $('navbar').removeClass('fixed-nav').next().css('padding-top','0');
   } 
});

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

Delete the div if it exists following another div and place it within the main div

<div class="error"> <input type="text" name="email"> <div class="error-message">Please Enter Email</div> </div> <div class="i-icon-div">Lorem Ipsum</div> I am trying to identify the div with the class of i-icon-di ...

The functionality of the jQuery scroll feature appears to be malfunctioning

I am trying to implement a scroll event and have written the following code: <script type="text/javascript> $(function () { $(window).scroll(function () { alert($("body").scrollTop()); }); }); ...

Instant data entry upon clicking

In an attempt to automate input based on image pairs, I encountered a challenge. On one side, there are two images that need to be matched with input fields, and on the other side, there are corresponding letters for each image to fill in the inputs upon c ...

Notification triggered in GridView editing according to authorization levels

I have a formview displaying data with an option to edit each row. There are different user roles in my system such as Admin, SuperUser, and User. If a non-Admin user tries to edit a row, I want to display a warning message. Currently, the JavaScript funct ...

Minimize the vertical gap between menu items when they wrap onto a new line

When examining the screenshot of the website, you'll notice a considerable space between the first and second rows of menu items. I'm aiming to minimize this spacing as much as possible. The following CSS pertains to this issue: .gva-navigatio ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

Prevent kids from disrupting the parent's hover state. (or how to use .stop(false,true) to halt a CSS transition)

When using jQuery's .animate() function to animate elements, it is important to use .stop(false,true) to prevent any unexpected animation issues. For example, I recently attempted to create a navigation menu that appears on hover of certain sections. ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

Having trouble with your UI Router states not updating correctly when changing the URL in your Angular UI Router?

I have tried numerous solutions and tutorials already with no success in finding the right answer. Therefore, I am posting here in hopes of receiving a fresh perspective and a little challenge. Using: angular ui router The Issue I have set up differen ...

Having trouble with image uploading in asp.net using the blueimp jquery file upload plugin?

I am experiencing issues with the blueimp jQuery file upload plugin example in C#. When I run the program, I am encountering errors and unable to upload files of any size. Any assistance would be greatly appreciated! Thank you in advance. Here are the de ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

In order to ensure that script assets in the app.blade file are updated with every route change, Laravel Vue Inertia requires

In my app.blade.php file, I have a script tag from CoreUI that looks like this: <script src="{{ asset('js/coreui.js') }}" defer></script>. However, I have noticed that the script is not being called on every route page, whic ...

Discover the step-by-step process of attaching middleware to events within socket.io

Is there a way to intercept middleware in Socket.io before passing it to an event handler similar to how it's done in expressjs? In other words.... In express.js you can use: app.get('/', middleware1, middleware2, function(req, res){ ...

Best approach for transferring data from Node.js/Express controller to pug view for subsequent processing with JavaScript

I am a beginner in the realms of Node.js, Express, and frontend development, and I am currently exploring ways to effectively process data transferred from a controller to a pug view for subsequent JavaScript processing. Presently, here is how the data pr ...

The error message is indicating that the entity "appId" reference needs to be terminated with a semicolon to resolve the blogger issue

Having some difficulty implementing a script in my blogger template to enable compression of the Facebook like box. Whenever I try to paste the code above (as I cannot find the appropriate tag) and click on save, I receive an error message in red. Can so ...

Exploring the angular $http module

How can one successfully access the $http object in angular.js? function MyController($scope) { $http... // not defined } ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

JavaScript does not run when triggered by ajax

How can I ensure that JavaScript code runs on a PHP page that has been loaded via an AJAX call? Code Example: Using AJAX and the function parseScript to force JavaScript execution on the requested AJAX page. Scenario: I am selecting a question from selec ...

Toggling Visibility of Divs within a Repeater Item Template

In each repeated row, I am showing a summary and detailed customer information inside the repeater. The summary content is contained within its own div with the ID "divHistory_Summary". The details are placed in a separate div with the ID "divHistory_Deta ...

Creating HTML for an email by iterating through a JavaScript object

I need assistance with iterating through a JavaScript object where each key:value pair is displayed on separate lines in the email body using Appscript. I believe it might need to be converted to an HTML string but I'm not entirely sure. The code snip ...