0

The code below takes the height of the navigation (50px, this is important for later) and the height of the viewport then sets the max-height of the image to be viewport height minus navigation height.

I do this so that the image will always be fully visible, no matter how tall it might be. Unfortunately, this has a small drawback.

Whenever I refresh the page, for a split second I could see the image before the JavaScript height has been applied. After comparing the difference in height using Photoshop, I realized the difference is exactly 50px which is the height of the navigation. This makes it clear that the image uses the CSS rules for a split second before the JavaScript kicks in.

Now my question is this - can I make it so that the image doesn't get displayed until the JavaScript manipulation has been applied to the image?

CSS

.specific-image {
    display: block;
    max-height: 100vh;
    max-width: 100%;
    margin: 0 auto;
}

JavaScript

function fitImage() {
        var navHeight = $("nav.navigation").outerHeight();
        var viewport = $(window).height();
        $(".specific-image").first().css({"max-height":viewport-navHeight});
}
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • How are you adding the image? i guess directly in the HTML? – tobifasc Oct 17 '18 at 19:22
  • The image is not hard-coded. It's image path is saved in a database and then I dynamically display it using PHP - Random image – Onyx Oct 17 '18 at 19:25
  • try leaving the src attribute blank in the HTML and adding the url using javascript after you changed the css. ([https://stackoverflow.com/a/1232804/2633917](https://stackoverflow.com/a/1232804/2633917)) – tobifasc Oct 17 '18 at 19:27
  • 1
    try setting `display:none;` initially for that class and change it to `display:block;` in your `fitImage()` method – vijay krishna Oct 17 '18 at 19:29
  • What Vijay Krishna suggested did work just fine. Could there be any drawbacks to using that? – Onyx Oct 17 '18 at 19:33

0 Answers0