Adjust the width of a div based on its height dimension

I have a div called #slideshow that contains images with a 2:1 aspect ratio. To set the height of the image using jQuery, I use the following function:

Keep in mind that the Slideshow Div is always 100% wide in relation to the browser window. If the user resizes the window, the slideshow will adjust accordingly.

slideWidth();

function slideWidth(){
var width = $("#slideshow").css("width");
var height = (parseInt(width.substr(0,width.length-2)) / 3);
$("#slideshow").css("height", height + "px");
}

In order to dynamically change the width, I utilize the setTimeout function like so:

setInterval(slideWidth, 1000);

This method is working as intended. However, I am concerned about the impact it may have on the website performance due to constantly refreshing the slidewidth function every second.

Is there a way to achieve this using CSS3 or with jQuery/JavaScript while minimizing the impact on the website?

Thank you. Please share any new ideas or suggestions you may have.

Answer №1

An innovative technique using only CSS involves utilizing pseudo elements and padding:

div {
    width: 100%;
    position: relative;
    background: blue;
}

div:before {
    display: block;
    content: "";
    padding-top: 60%;
}

By combining the pseudo padding-top, you can achieve flexibility with different aspect ratios.

For instance, setting the 60% padding results in an aspect ratio of 1.67:1.

See Demo on Fiddle

Answer №2

It is recommended to utilize jQuery's .resize() method as it allows for the addition of an event listener that awaits container resizing.

$(window).resize(function(){
  //implement your desired logic here
});

Learn more about the jQuery resize method

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

What is the best way to arrange div elements in this particular manner using CSS?

Wanting to create a specific layout for my website by positioning some divs in a unique way and adding content to them, I have been focusing on responsive design. I am wondering if it is possible to position these divs while ensuring responsiveness. The de ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Calculator: Show individual digits once more following a calculation

After clicking the 'equal' button, the result is displayed. However, if I click another number, it doesn't clear the result. I want the result to stay when operation symbols like '+' or '/' are pressed. While working on t ...

Showing JSON data in AngularJS

I need help with AngularJS to display JSON output. Is using gridOptions the best approach for this? I'm trying to print labels starting from the root in reverse order - label/parent's label/parent's parent's label/... { artifac ...

What steps can I take to make sure a particular node is successfully loaded and ready for use using JavaScript/jQuery?

When making a reservation at a hotel using the CJS Chrome extension, I am attempting to extract information about available rooms and rates both when the page loads and when the user changes dates. My current method involves injecting JavaScript into the p ...

"Despite using 'vertical-align: middle' on table cells, the alignment to the middle is not achieved when using AlphaImageLoader in IE6

I am currently working on aligning text within table cells that have a PNG Transparent background. To achieve this in IE6, I am using the filter:progid:DXImageTransform.Microsoft.AlphaImageLoader() method. However, I am facing an issue where the text is no ...

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

HTML5 canvas game issue: background fails to load

I'm a beginner at designing games using HTML5 canvas. I've been following a tutorial on creating games in the style of Angry Birds from the 'pro html5 games' book. I've completed all the steps in the tutorial, but I'm facing a ...

Problem with BehaviorSubject: next() method is not functioning as expected

My goal is to utilize an angular service for storing and communicating data via observables. Below is the implementation of my service: public _currentLegal = new BehaviorSubject({ name: 'init', _id: 'init', country: 'init& ...

How to Prevent Scrolling When Modal is in Use on Full Page JS

I am trying to achieve the functionality where when the modal is open, I want to prevent full-page scrolling in JavaScript. The issue arises when I open the modal and try to scroll, it ends up moving the content that's behind the modal, which is actua ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...

Iterating through a SASS map and retrieving the next item in the loop

I am working with a color array that looks like this: $colors: ( 'primary': '#aaa', 'secondary': '#bbb', 'color-3': '#ccc', 'color-4': '#ddd', 'color-5': & ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

Video is not visible in safari browser initially, but becomes visible only after scrolling for a little while

Having issues with a video not displaying correctly in Safari? The problem is that the video only becomes visible after scrolling the browser window. Want to see an example of this issue in action? Click here and select the red bag. Check out the code sni ...

Effective Ways to Redirect During or After Executing the onClick Function of Button

I am currently working on implementing a feature for my Next.js website. The functionality involves allowing users to create a new group by clicking a button, and then being redirected to an "Invite members" page with the auto-generated group_id included i ...

The backend is not receiving the variable through RESTful communication

I'm attempting to pass the word "hello" to the backend of my code using the URL. However, instead of sending the string "hello" to my Java backend code, it's sending an empty string. Below is my backend code: @GET @Path("getJob/{stepName}") @Pr ...

Is there a way to customize the font size of Material UI Autocomplete?

I'm currently trying to customize the Material UI Autocomplete component with my own CSS. Specifically, I aim to adjust the font size of the input field. Below is my current implementation: <Autocomplete style={{ width: 200, height: 60, ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...

Utilizing Jquery within Reactjs

Currently, I am encountering an issue while attempting to implement Materialize CSS in React JS. Some of the CSS components require jQuery for initialization or animation. Is it advisable to use jQuery in React JS? And if so, how can I incorporate jQuery ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...