3

Using FlexSlider on my site, I'm trying to get the height of the first image in the slider. I thought the following code would do the job, but it seems like the images are loaded very late, so that they have no height on this jQuery event. The code will return "0".

$(window).load(function() {
    $(document).ready(function() {
        var height = $(".flexslider>div>ul>li.flex-active-slide>a>img").height();
        console.log(height);
    });
});

But if I run this code in my browser console after the page has loaded, the correct height is returned.

How can I get the image height on page load/ready using jQuery or JavaScript?

Chris
  • 1,597
  • 4
  • 18
  • 26
  • 2
    By the way: window.load event occurs after document.ready, so your document.ready is pointless – reinder Feb 11 '13 at 10:35

2 Answers2

4

Thanks for clarifying that the window.load event occurs after document.ready, even though this had nothing to do with the actual problem.

The reason why the code returned "0", was due to a css-class in the default flexslider.css:

.flexslider .slides > li {display: none; -webkit-backface-visibility: hidden;} /* Hide the slides before the JS is loaded. Avoids image jumping */

The solution was to wait until the slider had loaded properly, by using the callback API:

$(window).load(function() {
    $(".flexslider").flexslider({
        start: function() {
            var height = $(".flexslider a>img").first().height();
            console.log(height);
        }
    });
});
Chris
  • 1,597
  • 4
  • 18
  • 26
1

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn't have to wait for all content to load.

See window.onload vs $(document).ready()

  $(document).ready(function() {  
       console.log($('.flexslider > ul > li > a > img').height()); 
  });

See DEMO http://jsfiddle.net/ducwidget/cufsn/1/

Community
  • 1
  • 1
Dumitru Chirutac
  • 617
  • 2
  • 8
  • 28
  • Thanks for clarifying that the window.load event occurs after document.ready, even though this had nothing to do with the actual problem. Please see my answer below. – Chris Feb 11 '13 at 13:30