Reputation: 146
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
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
Upvotes: 0
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