Animate the height and background color of a div element on scrolltop using JavaScript

Hello! I am currently working on designing my photography website and I have a cool feature in mind. I want the header to change as the user scrolls down the page. Here is how I structured the HTML menu/header:

<div id="menu" class="fluid">
    header/menu content
</div>

To style it, I used CSS to create a black background that is transparent and set a specific height for the menu:

#menu {
    height: 100px;
    background-color: rgba(0,0,0,0.1);
}

Now, with JavaScript, I managed to make the header collapse to 75 pixels when the user scrolls down more than 5 pixels. When they scroll back up, it expands back to 100px. This is the JavaScript code I used:

<script>
    // Minimize menu on scroll
    $(window).on('scroll', function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > 5) {
            $('#menu').stop().animate({height: "75px"},150);
        } else {
            $('#menu').stop().animate({height: "100px"},150);
        }
    });
</script>

I'm wondering if there's an easy way to adjust the background transparency along with the menu height changes. Since I don't have much experience with JavaScript, any guidance on what code to incorporate would be greatly appreciated.

Thank you in advance for your help! Apologies if this question has been asked before, I couldn't find relevant information using my search keywords.

Sincerely, Elmigo

Answer №1

To create animation using CSS transition, you can simply add the transition property to the desired element. In the example provided, opacity is used as an example and adjusted based on scrolling behavior.

It's worth noting that RGB color values are set instead of RGBA, with opacity being set to 0.1.

// Minimize menu on scroll
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 5) {
    $('#menu').stop().animate({height: "50px"},150);
    //$('#menu').css("opacity","0.8");
    $('div').css('background-color', 'rgba(0,0,0,0.8)')
}
else {
    $('#menu').stop().animate({height: "100px"},150);
    //$('#menu').css("opacity","0.1");
    $('div').css('background-color', 'rgba(0,0,0,0.1)')
}
});
#menu {
  height: 100px;
  background-color: rgba(0,0,0,0.1);
  transition:background-color 0.5s ease;
  color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu" class="fluid">
<p>gggg<p>
</div>
text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text
<br>text<br>text<br>text

Answer №2

In my opinion, the answer provided by amflare seems to be mostly accurate. To enhance it further, I would suggest eliminating the animate function from the JavaScript code and instead opt for the following approach:

CSS:

.darkerbg {
  height: 75px;
  background-color: rgba(0,0,0,0.5);
}

#menu {
height: 100px;
background-color: rgba(0,0,0,0.1);
transition: all 0.5s;
}

JAVASCRIPT:

if (scrollTop > 5) {
  $('#menu').addClass('darkerbg');
}
else {
  $('#menu').removeClass('darkerbg');
}

Answer №3

Create a new CSS class called "darkerbg"

.darkerbg {
  background-color: rgba(0,0,0,0.5);
}

Toggle this class based on scroll position:

if (scrollTop > 5) {
  $('#menu').stop().animate({height: "75px"},150);
  $('#menu').addClass('darkerbg');
}
else {
  $('#menu').stop().animate({height: "100px"},150);
  $('#menu').removeClass('darkerbg');
}

You can also handle the height changes in CSS using classes:

.menu {
  //various properties
  transform: all 0.1s; // for animation effect
}
.big {
  height: 100px;
  background-color: rgba(0,0,0,0.1);
}
.small {
  height: 75px;
  background-color: rgba(0,0,0,0.5);
}

Adjust the classes dynamically with JavaScript:

if (scrollTop > 5 && !$('#menu).hasClass('small')) {
  $('#menu').removeClass('big'); 
  $('#menu').addClass('small');
} else if (scrollTop <= 5 && !$('#menu).hasClass('big')) {
  $('#menu').removeClass('small'); 
  $('#menu').addClass('big');
}

Answer №4

To create a dynamic effect for changing the background-color, you can implement the jquery-ui plugin from jQuery UI. This tool has proven to be very beneficial and functions smoothly.

For instance:

Begin by incorporating jQuery UI into your project:

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="></script>

Next, update the Javascript code as follows:

<script>
// Reduce menu size when scrolling
$(window).on('scroll', function () {
    var scrollTop = $(window).scrollTop();
    if (scrollTop > 5) {
        $('#menu').stop().animate({height: "75px", backgroundColor: "rgba(0,0,0,0.5)"}, 150);
    }
    else {
        $('#menu').stop().animate({height: "100px", backgroundColor: "rgba(0,0,0,0.1)"},150);
    }
});
</script>

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

The window.frames function is coming back with a blank, empty

In an attempt to set up a simple HTML file on my local machine, I have the following code: <html> <head> <title>Testing</title> </head> <frameset framespacing="0" frameborder="0" rows="20px,100%" border="0"> ...

Fetching data from the database and seamlessly displaying it in a single view with the help of jQuery within the ASP.NET MVC framework

Currently, I am working with asp.net MVC to develop an application. In this project, I have a view that requires a treeview in the left pane and the details of the selected node item to be displayed in the right pane. The left pane's table represents ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

Tips to maintain the integrity of "text-decoration: underline" when adding positioning to the child <span> element

Explaining the rationale behind it, I have opted for relative positioning on <span> within <a> to make a slight adjustment in the text position enclosed by <span> (raising it 2px higher than its default placement). However, this causes th ...

Creating a design that can adapt to different screen sizes by utilizing CSS

On standard computer screens, my div has a height of 100%. However, for mobile screens, I would prefer not to have the height set at 100%. Is there a way to remove the height: 100% that was originally set for regular screens using CSS media queries? ...

Does the ngIf directive cause a re-evaluation of variables when used with one-time-binding in AngularJS?

I recently had a colleague at work demonstrate a peculiar quirk with one-time binding in Angular. Scenario: Imagine having an element with text being bound using one-time binding inside a block that is conditional on ng-if. If you update the value, say b ...

Is the execution of renderer.render() synchronous or asynchronous?

In my quest to capture a screenshot after each rendered frame, I have noticed some duplicates. This has led me to suspect that I may be saving the screenshot before the rendering process is fully completed. Therefore... Is it possible for renderer.rend ...

Transform an array of IDs into an array of strings using a list of objects

var myIds = [3, 4, 2]; var myObj = [ {id:1, name:'one'}, {id:2, name:'two'}, {id:3, name:'tree'}, {id:4, name:'four'}]; // need to obtain ['tree', 'four', 'two'] var ...

Is it possible to change the text displayed when hovering over various images using just CSS and HTML?

I have created an image and text hover effect. There are four images and corresponding paragraphs for each image. When hovering over an image, the specific paragraph should replace the previous one using only HTML and CSS. Please note the following: The de ...

The componentDidMount method does not seem to be getting invoked

When I tried to make an ajax request using this.props.getPostListData(this.props.lang), I encountered an error. After some investigation, I realized that the issue lies with the componentDidMount method. It seems that componentDidMount is not being cal ...

The background opacity feature is functioning properly in Internet Explorer 7 and 9, however it is not working

My primary CSS file contains the following: #wrapper { width: 760px; margin: 0 auto; padding: 20px; /* Fallback for web browsers that do not support RGBA */ background: #ffffff; /* RGBA with 0.8 opacity */ background: rgba(255, ...

A guide on setting background images with the img tag

I have created a PHP method that generates an HTML IMG tag. For example, ImageClass::getImage('sample.png' , 'myTitle') will output the string <img src="sample.png" title="myTitle" /> In my CSS file, I have used the following cod ...

Is there a way for me to make the two form fields expand and fill the gap between them?

I've created a form with the first name and last name fields displayed horizontally next to each other, as shown in the image. When a user clicks on a field, it should change color (still pending coding). However, there seems to be an unwanted gap be ...

quirky behavior of form inputs on mobile devices in a responsive webpage

I encountered a strange issue while developing a responsive webpage with form input. Whenever I tapped on an input field on my mobile phone to enter something, the screen would zoom in and cut off the text box on the left side, making it impossible to see ...

Challenge with jQuery UI Draggable: Div moves slower than mouse cursor

My issue is that when I move the mouse, the mouse moves faster than the div underneath it. I am using jQuery UI 1.12.1 and jQuery 3.3.1 with default options. Here is my HTML: <div class="popup"></div> And here is my jQuery code: $(function( ...

Trouble with displaying a cube from Blender to Three.js

Hey everyone, I'm having some trouble exporting a cube from Blender to three.js. I've exported the JSON file, but when I try to display the cube in my code, it's not showing up - instead, all I see is the setColor screen and I can't fig ...

When using .NET HtmlButton, validators will always be triggered

Recently, I converted an HtmlButton into a server control with validation disabled. <button runat="server" causesvalidation="false" /> This is not referring to the input button!!! <input type="button" runat="se ...

A comprehensive guide to resolving the [Vue warning]: props are required to be strings when utilizing array syntax

Here is my perspective : <div class="col-md-8"> ... <star :value="{{ $data['rating'] }}" :user="{{ $data['user_id']></star> ... </div> This is how my star component looks like : <template> ...

Tips for effectively utilizing the else if statement in JavaScript

My current script for submitting a form using jQuery Ajax is mostly functioning as expected. However, I am experiencing an issue where only two responses are being triggered. The loading component works correctly, but the other response statements, includi ...

Is there a way to superimpose multiple PNGs and ensure that each one is clickable within its designated area?

I am looking to implement a interactive image system for dynamically generated content. The image includes a background image and various grey-scale mask images. Background Image: https://i.sstatic.net/NWzQ1.jpg (source: goehler.dk) Masks: https://i.ss ...