Adjust the height in proportion to the width

My goal is to adjust the height of the li's based on their width using JQuery.


var width = $('li').width();
$('li').css('height', width + 'px');

However, I've encountered an issue as it doesn't result in the exact same size.

JSFiddle Link


$(document).ready(function () {
"use strict";

var width = $('li').width();

$('li').css({
'height': width + 'px',
        'background-color': 'green',
});
    
    $(window).resize(function(){
   $('li').height(width);
});
});

html, body {margin: 0; height: 100%}

div {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
}

ul {
padding: 0;
margin: auto;
width: 70%;

display: inline-flex;
flex-flow: row wrap;
justify-content: flex-start;
align-items: flex-start;
align-items: center;
align-content: center;
}

li {
list-style-type: none;
border: 1px solid tomato;
box-sizing: border-box;
flex-basis: calc(100%/3);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <ul>
    <li>1</li>
        <li>2</li>
        <li>3</li>
    <li>4</li>
    </ul>
</div>

Answer №1

Perhaps unconventional, but give this a shot:

$(document).ready(function () {
    "use strict";

    var size = $('li').width();

    $('li').css({
        'height': size,
        'width': size,
        'background-color': 'green'
    });
    $("li").height($("li").width());
    $("li").height($("li").width());

    $(window).resize(function () {
        var size = $('li').width();        
        $('li').css({
            'height': size,
            'width': size,
            'background-color': 'green'
        });
        $("li").height($("li").width());
        $("li").height($("li").width());
    });
});

Fiddle: http://jsfiddle.net/abcde12345/1/

Answer №2

When working with jQuery, it's important to note that the width() function rounds values to integers by default. To overcome this limitation, I have opted to use getBoundingClientRect() instead, as it supports decimal values.

Give this code snippet a try:

$(document).ready(function () {
    "use strict";

    var element = $("li");
    var newWidth = element[0].getBoundingClientRect().width;

    $('li').outerHeight(newWidth);
});

If you need the resizing functionality to be triggered on window resize events:

$(window).resize(function(){
    var element = $("li");
    var newWidth = element[0].getBoundingClientRect().width;

    $('li').outerHeight(newWidth);
});

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

Making a switch from one image to another - JavaScript

I need a solution to swap out an image that is used in multiple locations on a webpage. Consider this sample HTML page: <html> <head> </head> <body> <img id="1" src="example.com/img/1889.png"> <d ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Use the jQuery library to detect scrolling and toggle the CSS class between 'selected' and

I am trying to dynamically add the "selected" class to a[href] when a specific DIV comes into view while scrolling. However, I want to remove this class completely once the DIV has been scrolled past. const links = $(".cd-faq-categories li a"); // Find al ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

Calculate the total value of each individual subject from the checkbox's data-id, presented in a string format and separated by commas

<div> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, "> <label class="custom-control-label" for="Q_1_ck1"> ...

Encountered an issue with md-autocomplete: Attempting to read property 'success' of an undefined element

I encountered an issue while using Material Angular framework and md-autocomplete. The error message I receive is: Cannot read property 'success' of undefined. Below is the snippet of my code: /*My app.js*/ var app = angular.module('app&apo ...

Iterating through data to showcase vertical columns for a specific time span of 3 years, highlighting only the months with available data

If data has been available for every month over the past 3 years, I need it to be displayed in a specific format. You can refer to this example fiddle for reference: https://jsfiddle.net/bthorn/ncqn0jwy/ However, there are times when certain months may no ...

Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); In the controller, this is what I did: [Route("/api/[controller]")] [ApiCon ...

How can we leverage jQuery deferred within Backbone Marionette composite views, where each items view contains a form, to execute a task after each form submission is successful?

I am utilizing a Backbone Marionette composite view in which each child item view contains its own form. var DependentsFormFields = Backbone.Marionette.CompositeView.extend({ template: 'dependents_form_fields_wrapper', itemViewContainer: ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

Tips for organizing and nesting form data

Can I format my data in JSON like this: { attachments: { file: [ { name: 'pic1.jpg' }, { name: 'pic2.png' } ], username: 'Test', age: 1 } } Is it achievable us ...

Are there alternative methods for utilizing ionicons without needing the <script> tag?

In our workplace, the designer opted to incorporate ionicons but the documentation only provides instructions on how to use them without Ionic: Insert the following <script> at the end of your page, right before the closing </body> tag, to ac ...

Another ajax function implemented for a different form is experiencing technical issues

I have two forms with different IDs (form_sign and form_login) and I am using AJAX to submit them. The form_sign is working fine, but the other form is not functioning properly. When I tried to display an alert after submitting the form_login function, it ...

What is preventing me from modifying database information by deselecting checkboxes in CodeIgniter?

Recently, I came across a simple forum project on a website: CIBB Basic Forum with Codeigniter However, I encountered an issue while working on this project involving checkboxes. The problem seems to stem from the original code provided on the website, a ...

TemplateUrl malfunctioning

While experimenting with basic Angular code, I encountered an issue where everything was functioning correctly when using template, but not when switching to templateUrl. I did not provide the previous code as it was working fine except for this specific c ...

"Embed" three.js within SmartMS

Is it possible to incorporate this simple three.js example into Smart Mobile Studio without extensive wrapping? I attempted to copy the window.onload content into an asm section but was unsuccessful. <!DOCTYPE html> <html> <head> <t ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...