FlexSlider: How to get the height of an image on page load using JS or jQuery?

Using FlexSlider on my site, I am trying to get the height of the first image in the slider. I thought the following code would do the job, but it looks like the images are loading very late so that they have no height in 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 the browser console after the page has loaded, the correct height is returned.

How can I get the height of an image on the upload / download page using jQuery or JavaScript?

+3


source to share


2 answers


Thanks for clarifying that the window.load event occurs after document.ready, although this has nothing to do with the real problem.

The reason the code was returning "0" was due to the default flexslider.css css class:

.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 for the slider to load properly using the callback API :

$(window).load(function() {
    $(".flexslider").flexslider({
        start: function() {
            var height = $(".flexslider a>img").first().height();
            console.log(height);
        }
    });
});

      

+4


source


The ready event fires after the HTML document has loaded, while the onload event fires later when all content (like images) is also loaded.

The onload event is a standard DOM event, and the ready event is jQuery specific. The purpose of the prepared event is that it should appear as early as possible after the document has loaded, so that code that adds functionality to page elements does not have to wait for all of the 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/

+1


source







All Articles