Adjust the height or apply animation to the default CSS height using jQuery

I have a responsive website with different height settings for a header bar. In my JavaScript, I change this value to a fixed size at one point:

$('#header').animate({marginTop: 0, height:80});

But later in my code, I want it to revert back to the original state. How can I animate it back to its default behavior by removing inline CSS properties?

I attempted this:

$('#header').animate({marginTop: 20, height:'inherit'});

However, this approach did not work.

The original CSS for the header is as follows:

#header { margin-top:20px; width:100%; height: 80px; background-color: #000; }
@media only screen and (min-width: 768px) and (max-width: 960px) 
{   
#header{height:100px;}
}
@media only screen and (max-width: 767px) 
{
#header{height:auto; padding-bottom: 1px;}
}

Failed solution 1:


Storing the height value:
This approach is unfeasible due to users resizing their windows between storing and restoring the value.

Failed solution 2:


Animating to 'nothing', an empty string, fails because jQuery interprets it as 0 and animates the height to zero pixels.

Answer №1

Here is an example of how you can achieve this:

let height = $('#title').css('width');// retrieves original width

$('#title').animate({marginLeft: 0, width:120});

To revert back to the original state, you can do the following:

$('#title').animate({marginLeft: 0, width:height});

Answer №2

If you are working with HTML that looks like the following:

<div class="item">
    <div class="block"></div>
    <div class="info">
           My information
    </div>
</div>

You can implement a feature like this:

jQuery(document).ready(function($) {
    $(".item").mouseleave(function(){
        $(this).find('.info').stop().css('marginTop', '0');
    }).mouseenter(function(){
        $(this).find('.info').animate({ marginTop: '-50px', opacity: 0.5 }, 1000);
    });
});

Check out the demo for reference.

Answer №3

Experiment by removing the height value or replacing it with an empty string: `height: ' '`

Answer №4

To ensure the original value is saved, I suggest following this method:

$('#main-content').data('width', $(this).width()).animate({marginLeft: 10, width:150});

When you need to revert back to the original value, use this code:

var initialWidth = $('#main-content').data('width');
$('#main-content').animate({marginLeft: 20, width: initialWidth });

UPDATE --

Are there any other inline styles applied to the element?

If not, you can simply utilize removeAttr to eliminate the style attribute.

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

Unveiling the Magic of Knockout.js: Extracting the Object Data

I recently started experimenting with knockout and have a query. Here is an excerpt of the code: function Task(data) { var self = this; self.name = ko.observable(data.name); } function ViewModel() { self.taskArr = ko.observableArray([ // ...

HTML file unable to connect with CSS stylesheet

I'm facing an issue where my CSS stylesheet and HTML files aren't linking properly. Here is the code snippet from my HTML file: <head> <title>Website Sample</title> <meta charset="UTF-8"> <meta http-equiv= ...

Issues in invoking WebServices using Javascript in ASP.NET

I can't seem to figure out why I am unable to call a webservice. What could I be missing? @@ I'm attempting to follow the instructions provided here: How to call an ASP.Net Web Service in javascript Below are my codes, but they are failing to w ...

List Elements Not Displaying Correctly due to CSS Styling Issues

After spending several hours trying to solve this problem, I've hit a roadblock. The challenge lies in dynamically adding items to a list using JavaScript and the Dojo library. I've experimented with both vanilla JS and Dojo code, ruling that pa ...

Trouble with activating dropdown toggle feature in Bootstrap 5

I recently upgraded to Bootstrap 5 and now my code is not functioning properly. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria- controls="navbarCollaps ...

Using Javascript to invoke a PHP function and retrieve the response

This particular post showcases a sample code for fetching a server file list as an illustration. Below is the code that was utilized: <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Guidance on creating form using jQ ...

Is there a way to automatically trigger onClick events to repeat or make functions auto repeat?

The current situation is as follows: I currently have a button that, when clicked, sends its ID to a PHP page. The table is then cleared and a new table is printed in the column. The issue I am encountering now is that I want the table to be automaticall ...

Changing font color of a selected item in Material-UI's textview

I have a select textview in my react app and I am wondering how to change the font color after selecting an item from this textview. <div> <TextField id="standard-select-currency" select fullWidth l ...

What is the compatibility of Angular 2 with jQuery?

Was there an expansion in the subset of jQuery supported by Angular 2 compared to jqlite in Angular 1? Additionally, does Angular 2 still allow for direct injection of jQuery? ...

Is it possible to utilize the userId instead of the jwt token in this scenario?

Is it a good practice to hash the userId and store it in local storage, then send unhashed user id in authorization header on every route for server-side validation? Will this approach ensure security? ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

Add the "multiple" attribute to ui-select only if certain conditions are met

I am attempting to dynamically add the multiple attribute to a ui-select directive based on the value of a specific property by using the ng-attr- directive. Unfortunately, this method is not functioning as expected in my case. To better illustrate the iss ...

Selecting Radio Buttons using Selenium with Java

Having trouble locating the XPath for checking radio button selection in Selenium with Java. I am attempting to determine if the "one way" checkbox is selected, and if so, select the two way checkbox. However, each time I run the code, it only recognizes t ...

The Material-UI DataGrid feature allows for the display of column sums, with the sum dynamically updating based on applied filters

I am struggling with calculating the sum of values in the Total Amount column of my Material-UI DataGrid. How can I achieve this and ensure that the sum is also updated when a filter is triggered? Any guidance on how to sum the entire Total Amount column ...

Adding and Deleting HTML elements using jQuery

How can I use jQuery to add a line of HTML to existing HTML and then remove it? Here is the initial code: <div class="form-group"> <label class="control-label col-md-2" for="txtCvc">Cvc</label> <div class="col-md-10"> ...

How to properly center a div within another div using Internet Explorer

Here is the code I am working with: #div1 { position: relative; width:800px; height:540px; top: 50%; left: 50%; margin-top: -270px; margin-left: -400px; } #div2 { position:absolute; left:69px; top:223px; width: ...

Conditional statements in jQuery for identifying a specific div based on its id

My current setup involves an HTML table that gets populated based on a mysql query. The table is enclosed within: <div id="punchclock" class="timecard"> I also have a jQuery script in place to calculate the totals of the times entered into this tab ...

Having trouble getting Jquery Ajax Post to work properly when using JinJa Templating?

Objective: My goal is simple - to click a button and post information to a database. Problem: Unfortunately, clicking the button doesn't seem to be posting to the database as expected. Setup: I am working with Flask Framework, Jquery, and Jinja Temp ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

How to Use jQuery Post Method to Submit a Form Without Redirecting

I am looking to enhance the user experience of my form by preventing it from reloading upon submission. Specifically, I want to trigger the call to index.php when the submit button named "delete-image" is clicked in the scenario outlined below. It's i ...