Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, I used CSS code with width:100%; height:auto; so that all images are loaded with the same width (100%) but varying heights. I then implemented JavaScript to calculate the height of the image with the maximum width/height ratio and set it as the height for all images. Finally, I used width:auto; height:100%; to ensure that all images fit the calculated height.

The HTML structure for each slide includes the following:

<div class="img">
      <img src="" alt="">
 </div>

Here is my CSS code:

.img{
     position: relative;
     vertical-align: middle;
}

.img img{
     width: 100%;
     height: auto; 
     position: absolute;
     top: 0;  
     bottom: 0;  
     left: 0;  
     right: 0;  
     margin: auto;
}

And here is the JavaScript code:

$(".img img").width = "100%";
$(".img img").height = "auto";;
var img_h , Imgs_heights=[], ratio=[];
slider.item.find(".img img").each(function(){
    Imgs_heights.push($(this).height());
    ratio.push($(this).width()/(($(this).height())));
});
img_h = Math.max.apply(Math,ratio);
var i = r.indexOf(img_h );
$(".img").height(Imgs_heights[i]);
$(".img img").css("height", "100%");
$(".img img").css("width", "auto");

While everything works well initially, I encounter an issue when resizing the window. The height of the images does not change dynamically upon resize and requires a page refresh to display the desired result. I tried adding extra lines in the JavaScript to enforce width:100%; height:auto; on resize, but it did not resolve the problem.

Any assistance in resolving this issue would be greatly appreciated.

Answer №1

It seems like you are asking if it's possible to use the Javascript window.resize event to dynamically adjust the sizes of images on a webpage.

You can refer to Mozilla's documentation on https://developer.mozilla.org/en-US/docs/Web/Events/resize for more information about how the resize event works.

The resize event is triggered when the document view (window) is resized.

Your code could potentially be modified as follows:

function resizeImages(){
   $(".img img").width = "100%";
   $(".img img").height = "auto";
   var img_h , Imgs_heights=[] , ratio=[];
   slider.item.find(".img img").each(function(){
       Imgs_heights.push($(this).height());
       ratio.push($(this).width()/(($(this).height())));
   });
   img_h = Math.max.apply(Math,ratio);
   var i = r.indexOf(img_h );
   $(".img").height(Imgs_heights[i]);
   $(".img img").css("height", "100%");
   $(".img img").css("width", "auto");
}

window.onload = function(){
  resizeImages();
};

window.onresize  = function(){
  resizeImages();
}; 

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 PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

Is it necessary to implement the useCallback hook along with React.memo for rendering optimization in React components?

As I delved into understanding how useCallback and useMemo function in React to optimize app performance, I decided to create a simple app for experimentation. What I observed was that the callback function (OnBlurHandler) passed to my child component trig ...

Paste a data point from an Excel spreadsheet into a JavaScript script

I'm encountering a major challenge. Currently, I am creating a login process for a client and here is the approach I have taken: function Jump(pal){ if (pal=='10528'){window.open('http://www.google.es','_parent')} Subs ...

Placing additional text beside a nicely aligned box

I am struggling to figure out how to position text in the center left of a box that is located in the top right corner of my HTML template. <table class="label"> <tr> <td class="sign">F</td> ...

Load ajax content dynamically based on the updated URL

Exploring ajax for the first time and having some issues. Currently, I am retrieving text from files based on the URL. This is how it's set up: var home_url = "blahblah/index.html#home"; var test_url = "blahblah/index.html#test"; $(document).on("c ...

Switching out an element within a constrained array causes a momentary disappearance of the item

My playlist features artwork images that can be clicked. Upon clicking an image, the current track is replaced by the new selection in the array. An issue arises when Ember re-renders the items, causing a brief moment where the replaced element disappears ...

Encountering an error with an unknown variable while attempting to access a value from a JSON object

I had second thoughts about asking this question for fear of receiving a down-vote, but after extensive research and hours of typing, I have decided to go ahead. My goal is to retrieve the values 37 and exampleoffice from a json object: {"officeId":37,"o ...

The ongoing battle between Carousel full page image slider and multi div slider in Bootstrap 4

I need a full-page carousel image slider in one div container and a multi-div slider in another div container on my homepage. Unfortunately, due to some conflicting class names (such as carousel slide, carousel-inner, etc.), they are interfering with each ...

Tips for preventing a valid instruction from being identified as an error in NetBeans

As I work on my socket.io and node.js system in NetBeans 7.2, I encounter an issue every time I input a correct instruction like: io.sockets.in(channel_id).emit('new user', data); The problem lies in the ".in" part, which triggers an error high ...

Troubleshooting ASP.NET Content Page Error: jQuery Object Expected

Currently working on designing a personal ASP.NET Web page, I have encountered an issue with making a sticky div using jQuery. Despite all my other jQuery functions functioning properly, the sticky div seems to be causing trouble. stickydiv.js $(document ...

Using the same conditional statement on multiple pages within a Next.js application

I'm currently working on a project with Next.js and I've encountered an issue when fetching data from my server using the useSWR hook. There are certain conditions that need to be met in order to display specific content on the page, as shown in ...

Malfunctioning Line in Apple Safari Causing ReactJS Issues

I am encountering an issue with my <div className={`${classes.center} ${classes.or}`}>OR</div>. It appears that this problem is specific to Apple Safari only. The alignment on the right side seems to be broken, although it works fine on Google ...

Tips on how to horizontally align an icon and text using Material UI

As a newcomer to Material UI, I am facing an issue where my icon and text are not aligned: What I'm aiming for: This is the code I have so far: <div style={{ display: 'inline-flex', VerticalAlign: 'text-bottom', Bo ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

React Nextjs implementation of a fixed navigation bar to stick at the top

Hello, I am experiencing some issues setting up a sticky navbar in Next.js. The current navbar doesn't seem to be functioning as expected. Is there anyone who can assist me with the code provided below? import React, { useEffect } from 'react&apo ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Issues with Disabling the Browser's Back Button with jquery

I have been attempting to prevent the back button from functioning in a specific Browser, Microsoft Bing. Interestingly, my code works only if I click somewhere in the window first. If I don't click anywhere and try to go back directly, it still allow ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

JavaScript if else statement with 3 different scenarios

I'm having trouble figuring out why this code isn't working. It seems like there might be a conflict between the testRed and testGreen functions. If that's the case, could someone please suggest a better approach to solving this issue? Code: ...