JQuery gets dynamic width of multiple elements when resizing browser

The title pretty much explains most of my question. I will provide some context.

I have something like this. (Simplified)

<ul> <li><img src="image1.jpg"/></li> <li><img src="image2.jpg"/></li> <li><img src="image3.jpg"/></li> </ul> 

each li alternates horizontally. For instance:

  [ ][ ][ ][ ] 

So, I already have this script that stretches the image height and maintains the aspect ratio. But now I need a script that will dynamically get the width of all images (or li) even after resizing the browser . As far as I understand, I need something like bubbles or event delegation. I do not know how to continue this journey in jQuery.

links to images in different browser settings. I'm talking about

Normal browser height

http://f.cl.ly/items/1O3w3M3l3b3a0z2B0U1w/image1.jpg

Reduced browser height

http://f.cl.ly/items/3y3K38243J063J1U2f1P/image2.jpg

+4
source share
3 answers

You need to hook into the resize event:

 $(window).resize(function(){ $('li img').each(function(){ console.log( $(this).width() ); }); }); 

If you want it to fire when the page loads, fire the resize event yourself:

 $(window).resize(function(){ $('li img').each(function(){ console.log( $(this).width() ); }); }) .resize(); 

Here's the fiddle: http://jsfiddle.net/39JFQ/


If you need the total of all widths, use this:

 $(window).resize(function(){ var totalWidths = 0; $('li img').each(function(){ totalWidths += $(this).width(); }); console.log(totalWidths); }) .resize(); 

Here is the script for this: http://jsfiddle.net/39JFQ/2/


You should replace the li img selector with something more specific.

+2
source

You need to make a window resize event event handler:

 $(window).resize(function(){ $('li').each(function(){ var width = $(this).width(); if(width > large){ $(this).find('img').attr('src', 'largeImage.jpg'); }else{ $(this).find('img').attr('src', 'smallImage.jpg'); } }); }); 

Do you find media queries for this? http://www.w3.org/TR/css3-mediaqueries/

0
source

Do you really need JavaScript? Why not just use responsive CSS to adapt the images:

 img { width: inherit; /* This makes the next two lines work in IE8. */ max-width: 100%; /* Add !important if needed. */ height: auto; /* Add !important if needed. */ } 

and use the percentage width in your containers.

To do this in jQuery, you need to attach a handler to the resize event. Use one of the methods described here or an example using the Response below. I would use $. Data to store width data.

 Response.action( function () { // Code in here runs on ready and on resize: $.each($('img'), function() { // Get width of element each element: var currentWidth = $(this).width(); // Store for access where you need it: $.data( this, 'lastWidth', currentWidth ); });//each });//action 

See: responsejs.com/labs/dimensions/ too.

0
source

Source: https://habr.com/ru/post/1393239/


All Articles