Element height not updated after jquery resize

When resized, it does not update the height. Once the load has set its height, it will not be updated, even though I am updating the variable.

If I take out the lines where it sets the height, then my variable is updated normally, but as soon as the height is set, it does nothing.

Where am I 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 the JS fiddle
https://jsfiddle.net/5c1za6xa/

+5
source share
2 answers

Include var hero_height = $('.hero-image').outerHeight(); into the window resizing 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); }); 
+1
source

You think about it too much! You don't need jQuery at all, just multimedia CSS queries .

Here is an example

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

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

  • Easier to read
  • It does not require javascript, so it will work for users / devices that do not support javascript (which was not nearly anyone these days). But not using javascript will also significantly speed up page loading time.
  • In general (starting with the release of CSS3) you almost never need to use javascript (or jQuery, for that matter) to customize the style. Therefore, since you are trying to change the style / appearance of the page, you should use CSS. Leave JS the dynamic functionality of your webpage, not the styles.
0
source

All Articles