Animate the menu as you scroll

I am attempting to create a jQuery top menu that adjusts its height based on the window scroll position. Using $(selector).css("height", "value") works fine, but when I try to animate it, it doesn't behave correctly. Here is my code. Thank you for your assistance.

<!DOCTYPE   html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<style>
</style>
<body>
    <nav style="background-color:red; height:100px;" class="navbar-fixed-top navbar navbar-default my-navbar">
    </nav>
    <div style="width:100%; height:2000px; background-color:blue;" class="content"> 
    </div>

    <script>
        $(document).ready(function(){
            $(window).scroll(function(){
                var top=$(window).scrollTop();
                if(top>10){
                    $(".my-navbar").animate({height: '50px'}, "slow");
                }else{
                    $(".my-navbar").animate({height: '100px'}, "slow");
                }
            })
        })
    </script>
</body>
</html>

Answer №1

Solution One:

To control the animation, utilize stop() with animation:

$(window).scroll(function(){
var top=$(window).scrollTop();
if(top > 10){
$(".my-navbar").stop().animate({height: '50px'}, "slow");
}else{
$(".my-navbar").stop().animate({height: '100px'}, "slow");
}
})

View Solution on jsFiddle


Solution Two:

Implement addClass and removeClass for better management:

$(window).scroll(function(){
var top=$(window).scrollTop();
if(top > 10){
$(".my-navbar").addClass('NavBar2');
}else{
$(".my-navbar").removeClass('NavBar2');
}
})

View Solution on jsFiddle

Answer №2

The issue at hand is not that it's completely non-functional, rather that it's not performing as anticipated. After a period of time, it seems to do the work expected of it. The issue lies in the fact that the previous animation continues to run when attempting to animate it again. To resolve this, it may be necessary to first stop the previous animation by utilizing the jquery method stop()

if(top>10){
    $(".my-navbar").stop().animate({height: '50px'}, "slow");
}else{
    $(".my-navbar").stop().animate({height: '100px'}, "slow");
}

I trust this information proves helpful.

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

Can you explain the meaning of -ms-value?

I recently came across a solution for an issue specific to IE, and it worked perfectly for me. You can find the solution here: Change IE background color on unopened, focused select box However, I'm still puzzled about the meaning of -ms-value. Any i ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Using jQuery, select the line immediately following the last `<br>` tag and apply a `<span>` tag to style it

Current code snippet to work with: <div class="desc-wrapper">Dr <br> Credentials<br> Lecturer</div> I am trying to extract the text following the last <br> tag and then insert <span></span> between Lecturer in or ...

Steps for creating an expandable menu in the Magento category list

Looking for a way to create a category menu that expands when clicked on? Check out this example of a left menu (not Magento) at Can this be achieved with CSS alone? Or is there a specific module that can help with this functionality? ...

Encircling the icon with a circle

My styling skills are limited, but I'm attempting to create a marker that resembles the image linked below: https://i.stack.imgur.com/wXkaq.png. So far, I've made some changes in the code snippet provided, but I'm struggling to get it to d ...

Creating a dynamic dropdown list with PHP and AJAX using JQuery

I was attempting to create a dynamic dependent select list using AJAX, but I am facing issues with getting the second list to populate. Below is the code I have been working with. The gethint.php file seems to be functioning properly. I'm not sure whe ...

problem with using jquery's $.post function

I have set up a local server using express.js. The server sends an HTML file, and when I click a button, it should call a server-side API to get a result. However, I noticed that when I use $.post, it sends an empty body ({}) to the server. Server-Side Co ...

Is your margin not functioning correctly? Is padding taking on the role of margin?

One issue I'm encountering is that the margin isn't behaving as expected in this example. The padding seems to be working like margin should. Why is that? Print Screen: https://i.stack.imgur.com/N1ojF.png Why is it that the margin in the h3 ta ...

Utilizing carouFredsel for thumbnails and compatibility with IE7

I've successfully integrated carouFredSel (using the basic example with next/prev and pagination) on Chrome, Firefox, IE9, and IE8. However, when I tested it on IE7, the plugin didn't seem to work correctly. The list just displayed vertically wit ...

Adjustable height and maximum height with overflow functionality

Currently, I am in the process of developing a task manager for my application and facing an obstacle when trying to calculate the height of a widget. My goal is to determine the maximum height (assuming a minimum height is already set) by subtracting a ce ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Exploring the Depths of JSON Arrays using jQuery

Apologies for the simple question, but I need help with accessing a deeply nested URL node in JSON. I am converting an RSS feed to JSON using the jGFeed plugin. Currently, I can only get attributes at the parent level by using "console.log("feeds.entries[i ...

The event type of jQuery's hover is displayed as mouseover and mouseenter

Check out this picture: Do you think this is a bug or the norm? Please note that 'mouseover after args' is just a label. Capture Event $ -> $('.bigger-on-hover').hover (event) -> console.log 'args' console ...

Eliminating redundancy in an array to enhance autocomplete functionality

I'm facing an issue where my array contains a combination of numbers and alphabets, and I need to remove duplicates for my autocomplete feature. I have tried using $.unique from jQuery, which works fine on Chrome but not on IE10. Any suggestions on ho ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

Guide on altering the cursor icon during an AJAX operation within a JQuery dialog

When I have a JQuery dialog open and make some $.ajax calls, why can't I change the cursor? I want to display a progress cursor while the code is processing so that users can see that the action is still ongoing. However, even though I update the CSS ...

Ways to reduce the size of the background image in a select element?

Utilizing the bootstrap form-select select element : <select class="form-select listbox_length_menu_datatable" <option value='5'>5</option> <option value='10'>10</option> <option value ...

Struggling to implement CSS variables across different browsers

I'm struggling to make CSS variables function properly, here is what I have so far: :root { --primary-color: #ffcd600; --spacing: 10px; --blur: 10px; } img { padding: var(--spacing); background: var(--primary-color); } When I check the el ...

Is it possible to adjust the dimensions of the number input spinner?

When working with a number input that includes a spinner, I have encountered challenges in changing the size of the spinner itself. Specifically, I am referring to the <input type='number'> element. Despite my efforts to adjust its size thr ...