Implementing jquery to dynamically adjust the height based on certain conditions

When resizing the window, if the height of #cat is less than the height of #dog, the height of #cat should be set equal to the height of #dog.


$(window).resize(function() {

if ( $('#cat').height() < $('#dog').height() ) {

    $('#cat').height( $('#dog').height() );

} else {
  
    // Do nothing

}

What would the proper Jquery code be?

Could someone please assist me with this? Thanks!

Answer №1

Here's a different approach:


$(window).resize(function() {
 var catHeight = $("#cat").height();
 var dogHeight = $("#dog").height();
 if(catHeight < dogHeight) {
  $("#dog").height(catHeight);
 }
});

Answer №2

To tackle this issue, you can utilize the Math.max function instead of relying on an if statement. It's also advisable to debounce the resize event in order to prevent any jittery behavior in the UI during window resizing. Give this a try:

var resizeTimer;
$(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
        var $cat = $('#cat'), $dog = $('#dog');
        $cat.height(Math.max($cat.height(), $dog.height()));
    }, 100);
});

Check out the live demo here

Answer №3

This could be the solution you've been searching for.

$(window).resize(function() {
    if ( $('#cat').height() < $('#dog').height() ) {
        var dogHeight = $('#dog').height()
        $('#cat').height(dogHeight)
    }
})

If there is no expected action in the else statement, it can be omitted.

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

Performing numerous database insertions in Laravel 8

I am facing an issue where I need to add multiple rows to a database table. The database consists of two tables: projets and projets_castiong. The first set of input fields in the form should be inserted into the projets table, while the second set of dyna ...

Easily transfer a Jquery array to a Rails controller action!

I'm struggling to understand how to send a query in JSON format to a Rails controller#action. Here's what I have: var myarray = []; ( with values ) This is the controller action I want to post to: def process end I've searched everywher ...

Adaptive selection choices determined by prior selections

After some reflection, I realized that my initial approach to a previous question was incorrect. I currently have an array of data that can be converted to JSON data if necessary. The data structure is as follows: array:4 [▼ "data" => array:2 [▼ ...

The response from Ajax in JavaScript may come back as undefined

I'm facing an issue with my JavaScript function that uses AJAX to call a PHP function inside a PHP class. The problem is that the console.log shows undefined. function SpinTimeTotal(){ $.ajax({ type:"POST", url: &qu ...

Dynamic expand/collapse animation in React with adjustable height feature

I'm currently working on an Expand component and attempting to implement an expand animation upon toggle without success. I want this animation to be dynamic without explicitly setting the element's height: export const Expand = ({ startOpen, con ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

What is the best way to programmatically activate a selectbox click within a function's scope?

I am currently developing a mobile app with phonegap, jQuery Mobile, and AngularJS. I am trying to activate a click event once I have clicked on another icon. To achieve this, I am calling a scope function where I have attempted using $('#id').c ...

What initiates Electron after npm processes the package.json file?

As I delve into the realms of JavaScript, HTML, and Electron, a particular question has been playing on my mind - what exactly happens when you run electron . in the "scripts" -> "start" section of package.json? The mysterious way it operates sends shiv ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

Struggle with Firefox: Table-cell with Relative Positioning Not Acting as Parent

Upon investigation, I have come across a unique layout issue that seems to only affect Firefox. It appears that elements with display:table-cell; do not act as the positional parent for descendants with position:absolute;. It is surprising to discover th ...

Ways to retrieve the innerHTML content in Mozilla Firefox

Look at this HTML code snippet: <div id="divTest"> Hello <input type="text" id="txtID" value="" /> <input type="button" onclick="getForm();" value="Click" /> </div> Also, check out this JavaScript function for retrievi ...

Inject JSON data into a jQuery plugin

Currently, I am exploring how to input settings into an animation plugin in the format below (I understand it may not be user-friendly to require users to tinker with settings like this, but a GUI will be developed alongside it): $('#animationContain ...

PHP is not compatible with cookies, however, they can be effectively used with Javascript

In order to view the cart of products, I am looking to initially load it using PHP and then handle subsequent updates or deletions through jQuery post requests. However, I am encountering an issue. [I receive variables in JSON format within the same PHP ...

What is the best way to search for unique fields in MongoDB using Node.js?

Explore the contents of my imageDetails database: > db.imageDetails.find() { "_id" : ObjectId("5a187f4f2d4b2817b8448e61"), "keyword" : "sachin", "name" : "sachin_1511554882309_1.jpg", "fullpath" : "Download/sachin_1511554882309_1.jpg" } { "_id" : Objec ...

Transform your CSS3 rotateY into PHP Imagick::distortImage

I'm trying to rotate an image by rotateY(-54deg) on the front-end, and now I need to achieve the same rotation in PHP using Imagick::distortImage. $image->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true); Is there a straightfor ...

Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in ...

I am attempting to send a JavaScript array to PHP using Axios FormData, but I am consistently facing failures. Every time I check the console, I see [object Object] being displayed. I also tried using stringify ""

Hey there, I'm currently working on posting a JavaScript array consisting of keys and values to PHP using Axios but I am quite lost. Thank you in advance for your assistance. Below is the array that I am sending: let arr = []; arr["adID"] = uuid ...

After the image has loaded, Context.drawImage is failing to function

I am in the process of creating a freehand drawing application using the HTML canvas element. I am currently working on adding an 'Undo' feature, which involves saving snapshots of the canvas state each time the user draws something. When the use ...

Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus. Upon receiving the event, I trigger a method that fetches data using a Swagger client. The goal is ...