KINKWILDE
KINKWILDE

Reputation: 146

Element height not updating after jquery resize

On resize it doesn't update the height. Once the load has set it's height, it will then not update despite me updating the variable.

If I take out the lines where it sets the height, then my variable updates fine, but once the height is set it just doesn't do anything.

Where have I gone wrong?

var hero_height = $('.hero-image').outerHeight();
console.log('heroHeight: ' + hero_height);

$(document).ready(function() {
    $(window).load(function() {

        $('.hero-image').css('height', hero_height );

    });

    $(window).resize(function() {

        if (hero_height !== $('.hero-image').outerHeight()) {
            $('.hero-image').css('height', hero_height );
        };

        hero_height = $('.hero-image').outerHeight();
        console.log('heroHeight: ' + hero_height);

    });
});

Here is a JS fiddle
https://jsfiddle.net/5c1za6xa/

Upvotes: 6

Views: 1697

Answers (2)

nmg49
nmg49

Reputation: 1386

You're overthinking this! You don't need jQuery for this at all, just CSS media queries.

Here's an example

nav {
   display: block;
}

@media screen and (max-width: 480px) {
  nav {
    display: none;
  }
}

This will hide a nav bar on mobile devices (or technically, anything with a screen height of less than 480px). You can obviously change the max-width and styles to suit your needs. This is far superior to jQuery for a number of reasons

  1. It's way easier to read
  2. It doesn't require javascript, so it will work for users/devices that don't support javascript (which granted is almost no one these days). But not using javascript will also speed up your page loading time enormously.
  3. In general (since the release of CSS3), you almost never need to use javascript (or jQuery for that matter) to adjust style. Therefore, since you're trying to change the style/look of the page, you should use CSS. Leave the JS to dynamic functionality of your webpage, not styles.

Upvotes: 0

Ghayyour Ahmed Butt
Ghayyour Ahmed Butt

Reputation: 393

Include var hero_height = $('.hero-image').outerHeight(); in the window resize function.

$(window).resize(function() {
    var hero_height = $('.hero-image').outerHeight();
    if (hero_height !== $('.hero-image').outerHeight()) {
        $('.hero-image').css('height', hero_height );
    };

    hero_height = $('.hero-image').outerHeight();
    console.log('heroHeight: ' + hero_height);
});

Upvotes: 1

Related Questions