Tips for creating a dynamic menu with animated effects

Check out my fiddle here: http://jsfiddle.net/k3AHM/23/

$(document).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 110) {
            $('.menu-container').addClass( "fix-menu" ).animate('top', '-3px');

        } else {
            $('.menu-container').removeClass("fix-menu");

        }

    });  

When the menu becomes fixed, it's not as smooth as this demo: check it out here

What could be causing this issue in my code?

Answer №1

Perhaps you could consider incorporating my latest update: https://jsfiddle.net/k3AHM/37/

Here are the key changes I made: 1. Implemented a check to see if the animation function has already been executed to prevent repetitive calls on scroll. 2. Opted for slideDown() over the "animate" function for added interest, although you can still use "animate" if preferred.

Below is my revised code:

var AlreadyRun=0;  
$(document).ready(function(){
    $(document).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 110) {
            //$('.menu-container').addClass( "fix-menu" ).animate('top', '-3px');
            if(AlreadyRun == 0){
                AlreadyRun=1;
                //alert('function starts, AlreadyRun='+AlreadyRun);
            $('.menu-container').hide().addClass( "fix-menu" ).slideDown('slow');

            }
        } else {
            AlreadyRun=0;
            $('.menu-container').removeClass("fix-menu");

        }

    });
});

In addition, I believe eliminating the "transition" property in CSS is unnecessary, so I have updated the CSS as follows:

.menu-container {
   /* transition: all .3s ease-in-out; */
    background:red;
    margin-top:0;
}

.fix-menu{

    /* transition: all .3s ease-in-out;*/
    box-shadow: 0 5px 10px 0.5px rgba(0, 0, 0, 0.1);
    height: 54px;
    left: 0;
    top:0;
    overflow: hidden;
    position: fixed;
    right: 0;
    z-index: 1500;
    /* transition: all 0.2s ease-in; */


}

I trust this aligns with your requirements.

Answer №2

Transforming CSS Transition

Visit the JSFiddle here for a live demo.

let fixed = false;

$(document).scroll(function () {
    let y = $(this).scrollTop();
    if (y > 110) {
        if (!fixed)
        {
            fixed = true;
            $('.menu-container').addClass("fix-menu");
        }
    } 
    else 
    {
        fixed = false;
        $('.menu-container').removeClass("fix-menu");        
    }
});
.menu-container {
   transition: top .3s ease-in-out;
    background:red;
    margin-top:0;
    top: -54px;
}

.fix-menu{
    box-shadow: 0 5px 10px 0.5px rgba(0, 0, 0, 0.1);
    height: 54px;
    left: 0;
    overflow: hidden;
    position: fixed;
    right: 0;
    z-index: 1500;
    top: 0;
}

Dynamic jQuery Animation Solution

Here's a link to the interactive JSFiddle demonstration.

let fixed = false;

$(document).scroll(function () {
    let y = $(this).scrollTop();
    if (y > 110) {
        if (!fixed)
        {
            fixed = true;
            $('.menu-container').addClass("fix-menu").css('top', '-54px').animate({top: '0px'});
        }
    } 
    else 
    {
        fixed = false;
        $('.menu-container').removeClass("fix-menu");        
    }
});
.menu-container {
    background:red;
    margin-top:0;
}

.fix-menu{
    box-shadow: 0 5px 10px 0.5px rgba(0, 0, 0, 0.1);
    height: 54px;
    left: 0;
    overflow: hidden;
    position: fixed;
    right: 0;
    z-index: 1500;
}

Answer №3

Be sure to take a look at this fiddle: http://jsfiddle.net/k3AHM/24/

.menu-container {
  transition: all .3s ease-in-out;
  background:red;
  margin-top:0;
  top:-110px;  /* don't forget to include this */
}

If you specify a position for the 'top' property in the menu-container, your code will function smoothly.

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

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

Utilizing the Public Directory in Vite Compilation

One issue I encountered in my project with Vite version 2.9.7 is related to the handling of images stored in the public folder within the project's root directory. To import these images, I utilized Vite's import.meta.glob function, like so: imp ...

Unforeseen Firefox Problem Arises with display: table CSS Property

The ultimate visual aim is to create a horizontal menu with links that can span multiple lines but are all vertically centered. In modern browsers, this effect can be achieved using CSS with the display: table property. Here is an example of how it can be ...

An issue has been encountered in the code during the installation of react.js

node:internal/modules/cjs/loader:1148 throw err; ^ Error: Module 'C:\Users\hp\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js' could not be found. at Module._resolveFilename (node:internal ...

Is it possible to retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Hide Details tag only on mobile view

How can I easily close the default opened <details> tag on mobile? I am working with Wordpress. Any suggestions on how to achieve this? <details open> <summary>Details</summary> Something small enough to go unnoticed. </ ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Interactive Conversation Interface for Customer Communication

I've noticed on a lot of websites that companies often place contact forms, login or sign up forms in the lower right corner, similar to a chat box. When you hover and click on it, a full form opens up for users to submit data. I'd like to impl ...

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

Utilizing JQuery to Retrieve JSONP Data from WCF

Lately, I've been encountering difficulties with fetching JSON data from a WCF service application that I developed. The WCF service is pretty straightforward and returns the following JSON results: [{"RoomId":1,"RoomName":"Big Room"},{"RoomId":2,"Ro ...

An unexpected 'u' token was encountered in the JSON data at the beginning while parsing with NextJS from the router.query

I have successfully passed data through the URL path from my main page to my quotes page component in NextJS 13. However, I encountered an error when trying to refresh the page. Quotes Page Component import React from 'react' import { useRouter ...

PHP: Extracting the selected value from a dropdown menu and incorporating it into an HTML link

Initially, I created a dropdown list Yet, there is uncertainty surrounding how to incorporate the selected choice (variable) into the input of the HTML <p style="text-align:center"> COVID-19 Checker</p> <br> <label for ...

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

Utilizing jQuery to close a modal when clicking outside of its container

Trying to target elements in my practice layout but struggling to figure out the right approach: BASIC HTML <button id="opencontact" type="button" name="button"> <i class="far fa-envelope fa-2x"></i> </button> <section id="c ...

An effective way to emphasize the full area of a list item when hovering over it

Is there a way to modify the hover behavior of a list item in Fiddle? I'd like the black highlight to cover the entire area of the list item, without leaving any white space on top or bottom. Currently, it only covers the center area of the list item. ...

Google Locations API + React JS + Node.js data not returning

I would like to express my gratitude in advance for any assistance provided. I am currently exploring the development of an application using data from the Google Places web services API. I am utilizing AngularJS, PHP, and HTML for this project. Unfortunat ...

Is it possible to customize bootstrap classes for a unique bootstrap css design?

In my MVC4 project, I faced a situation where I had a global.css class with some classes that conflicted with Bootstrap after adding it. To resolve this, I created a new file called bootstrap_migration.css. In this file, I prefixed the Bootstrap classes wi ...

Sorting tables using ajax-generated data

I am having trouble with a table that is generated using ajax (PHP). Even though I have included all the necessary attributes for tablesorter, it doesn't seem to be working. Can someone please point out where I might have made a mistake? Any suggestio ...