Federico
Federico

Reputation: 1422

Check image width / height ratio continuously

I have this very simple but effective script that adds a class landscape or portrait to the img according to the width / height ratio.

$('img').each(function(){
$(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
});

The problem is that the website uses infinite scroll and when the second page is loaded the images won't be affected by the script.

Is there any way I can run the script continuously to check images proportions?

Thanks in advance.

Upvotes: 0

Views: 39

Answers (2)

Nico Zimmer
Nico Zimmer

Reputation: 328

Yes. There is any way. Set you function in you onscroll-event

$(document).scroll(function(){
   $('img').each(function(){
   $(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
   });
});

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50884

As per your request there is a way to check it continuously using setInterval, however I don't think that is the most efficient solution to a problem like this (for instance you may try and check for an onchange event on your body of your HTML). Here is the way you can by using setInterval:

setInterval(function() {
  $('img').each(function(){
    $(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
  });
  console.log("Updated images");
}, 1000 * 2); // Where '2' says it will run every 2 seconds (every 2000 milliseconds)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

Upvotes: 1

Related Questions