I'm terrible at anything Javascript, so I think this is really easy, but I think the way I'm searching for an answer is wrong. I'm trying to add a class with jQuery to images that are taller than they are wide (portrait). My jquery looks like this:
jQuery(document).ready(function($){
var imgs = $(".isLandscape");
imgs.each(function(){
var img = $(this);
var width = img.width();
var height = img.height();
if(width < height){
img.parent('li').addClass('portrait');
}
})
});
It works after I refresh the page after an initial page load. To clarify: Page loads for the first time, the .isLandscape
is not added to <li>
element. I refresh the page, .isLandscape
class is added to <li>
element and everything is how I want it to be on the first load. What am I missing?
A few things I've tried:
(window).on("load", function...
. instead of(document).ready...
and a few different variations.Loading the jquery in the
<head>
vs the in the `'a bunch of random stuff that I googled.
Some things that might help someone help me:
It's a wordpress site.
Obviously I'm terrible at javascript.
Thanks for your help in advance.
Edit
Thanks for everyone's help. The tip that helped me was I wasn't listening for everything to be completely loaded. This is my final code:
jQuery(document).ready(function($){
$(window).load(function(){
$(".isLandscape").each(function(){
var img = $(this);
var width = img.width();
var height = img.height();
if(width < height){
img.parent('li').addClass('portrait');
}
})
});
});
I needed to:
1. make sure the dom was ready jQuery(document).ready
.
- them make sure everything was loaded
$(window).load(function...
, which is the same as$(window).on("load", function()...
I believe.
Just a note for those who find this:
I tried instead of window
, using "img"
or ".isLandscape"
to see if the specific elements were loaded and neither worked. I think because there were many images and images with the class .isLandscape
on the page, but I'm not totally sure.