Modify the height of an element in real-time using jQuery

I'm looking to dynamically adjust the height of a div based on another element, but only if that element does not have the class collapsed (which is used in a Bootstrap toggle collapse feature).

The initial setup seems to work fine, however, when I interact with the element and the collapsed class is removed, the height of #careheight does not update accordingly.

$(document).ready(function() {
  var divHeight = $("#care_and_washing").height();
  if (!$("#care_and_washing").hasClass("collapsed")) {
    $('#careheight').height(divHeight);
  } else {
    $('#careheight').height("10px");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p>

<div style="cursor: default; padding-left: 13px;" id="demo" class="collapse">
  <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Dry Flat</p>
  <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Do Not Bleach</p>
  <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Tumble Dry Low</p>
  <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Iron Low</p>
  <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Hand Wash</p>
</div>

<div id="careheight"></div>

Answer №1

The reason for this is that the function is only triggered when the document loads. To make it work on click events as well, you need to attach it to a click event:

$(document).ready(function(){
    changeHeight();
})

$('.element-you-want-to-click').click(function() {
    changeHeight()
});

function changeHeight() {
    var divHeight = $("#care_and_washing").height();

    if (!$("#care_and_washing").hasClass("collapsed")) {
        $('#careheight').height(divHeight);
    }

    else {
        $('#careheight').height("10px");
    }
}

If your original function was effective, this modification should work properly.

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

Steps for creating a TypeScript class that can implement an interface

As a beginner in TypeScript, I am looking for help with the following code snippet: async function sleep(ms: number) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), ms) }) } async function randomDelay() { ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

Retrieve information from each row and extract the input values, as well as the attributes tr.data() and td.data()

Currently, I am exploring the usage of DataTables to see if I can successfully integrate it into my website. Despite searching on DataTables and Stack Overflow forums, as well as conducting Google searches, I have not come across a solution that addresses ...

Is there a way to prevent a 'keyup' event from being triggered by a 'keydown' event?

I have a tool that resolves zip codes and I am currently utilizing a keyup event handler to trigger a server query once the input length reaches 5 characters. However, I want to prevent unnecessary calls to the script, so I am exploring the possibility o ...

How do I use Puppeteer to save the current page as a PDF?

Is it possible to convert a web page in a React project to PDF and download it upon clicking a button? ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Request financial data from AlphaVantage using PHP

I'm currently working on utilizing the alphavantage API to retrieve currency exchange information. In order to obtain the desired data, I am using the following query URI: https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_cu ...

Footer void of color

It's puzzling to me where the extra space in my footer is coming from. It seems to be around 20-30px as you can see on the following url: Despite the code in my footer being minimal, with no apparent cause for this additional space below my social ic ...

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

event handling for multiple dropdown lists using jQuery and Ajax

I have a situation where I am using two drop down menus to filter some results. When the user changes the option in the first drop down, it should dynamically update the choices in the second one. I managed to replace the options in the second drop down, b ...

Using Rails to assign a page-specific CSS class within a shared layout

Is there a way to apply unique CSS classes to specific tags within a common layout? In my application.html.erb layout file, the application.css.scss is loaded using <%= stylesheet_link_tag "application". . . %>, which then includes all CSS files in ...

What is the best way to assign a jQuery variable to a PHP variable?

After spending some time searching and working on it, I still can't figure out the answer to this straightforward question. Here is the code I have been struggling with. <script> function calculate() { var total = (parseInt($('#stude ...

Utilizing Google Script to extract information from Gmail emails and transfer it to Google Sheets

I am facing a challenge with extracting data from an email and inputting it into a Google Sheet. While most of my code is functioning properly, I'm struggling with the regex section due to lack of expertise in this area. Below is a snippet of the HTM ...

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

Error encountered in react-test-renderer test due to TypeError: Attempting to access properties of an undefined variable, specifically trying to read the 'current

Having trouble with my unit tests using react-test-renderer. Even though the component I'm testing is working fine, the test won't pass. Can someone please help me figure out what I'm doing wrong? Below is the code for the component: // ...

What is the best way to show a message of success once the user has been redirected to the homepage?

Currently, I have a registration form utilizing AJAX and PHP for validation. Error messages can be displayed on the registration page if the user does not correctly fill out the form. Upon successful registration, the user is redirected back to the home pa ...

Elements are randomly glitching out with CSS transitions in Firefox

Chrome is working perfectly for me, but when I switch to Firefox it behaves differently than expected I am attempting to create a simple animation (utilizing transitions) that continuously runs on mouseover and smoothly returns to the starting position on ...

Exploring the World of Popper.js Modifiers

Within our React and Typescript application, we integrate the react-datepicker library, which utilizes popper.js. Attempting to configure PopperModifiers according to the example provided here: . Despite replicating the exact setup from the example, a typ ...

(discovered: [object Promise]) utilizing Material UI and DexieJS

Exploring DexieJS and Material UI for the first time has been quite a learning experience, so I may have overlooked a crucial aspect. Here is a glimpse of my code: Subscreen.tsx const [fightersArray, setFightersArray] = useState<FighterEntity[]>([]) ...

Here is a guide on determining the date variance in PHP by leveraging jQuery

I have been attempting to use the jQuery change function to calculate the variance between two dates, but I am encountering a problem as the code seems to be running smoothly without returning any results... <input type="text" name="datte1" class="form ...