4

I am using a jQuery script to add a class (portrait or landscape) depending on their dimensions. Then I am using jQuery to center the image vertically. The script works perfectly when I past it into the console, but not when I link it in the document head. Here is the code I have:

jQuery( document ).ready(
    function() {
        jQuery(".imgResize").each( function () {
            var $this = jQuery(this);
            if ( $this.width() > $this.height() ) {
                $this.addClass("landscape");
            } else if ( $this.width() < $this.height() ) {
                $this.addClass("portrait");
            } else {
        }
        var $h = $this.height();
        $this.css('margin-top', + $h / -2 + "px");
    });
});

What would cause this issue?

Tepken Vannkorn
  • 9,648
  • 14
  • 61
  • 86
jordan
  • 9,570
  • 9
  • 43
  • 78

2 Answers2

2

You need to wait for the images to be loaded

jQuery(document).ready(function () {
    jQuery(".imgResize").on('load', function () {
        var $this = jQuery(this);
        if ($this.width() > $this.height()) {
            $this.addClass("landscape");
        } else if ($this.width() < $this.height()) {
            $this.addClass("portrait");
        } else {

        }
        var $h = $this.height();
        $this.css('margin-top', +$h / -2 + "px");
    });
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Actually In your case, your jQuery Script is running before loading of the image. So, if you want to run your script on after loading the image.

Then you need to use jQuery Load

Solution

jQuery( document ).ready(
    function() {
        jQuery(".imgResize").on('load', function () {
            var $this = jQuery(this);
            if ( $this.width() > $this.height() ) {
                $this.addClass("landscape");
            } else if ( $this.width() < $this.height() ) {
                $this.addClass("portrait");
            } else {
        }
        var $h = $this.height();
        $this.css('margin-top', + $h / -2 + "px");
    });
});
Shivam Chopra
  • 639
  • 10
  • 20