Reputation: 37
I have created 2 responsive boxes, first box have a picture inside and the other one some text. Both have a width: 50%; and first box height: 100%. However.. whenever I resize the window, I want the box number 2 height to be the same with the one from box number 1.
I have created this jquery and it works, but it doesn't work when I resize the window. I think a solution to this may be for the jquery to be executed whenever I resize the window, but I don't have any idea how. This is what I have done:
<script>
var Box = $('.theElement');
$('.theElement2').css({ height: Box.height() });
</script>
Thank you for the advice! The final solution looks like this:
var Box = $('.theElement');
$(window).load(function() {
$('.theElement2').css({ height: Box.height() });
});
$(window).resize(function() {
$('.theElement2').css({ height: Box.height() });
}).resize();
Note: I had to introduce the load function because when I refreshed the page the jquery sometimes works, sometimes it doesn't. Now it works perfectly!
Upvotes: 0
Views: 50
Reputation: 66188
What you could do is to wrap the setting of the height in a function, and then call it upon DOM ready as well as upon the window resize event:
$(function() {
var setHeight = function() {
var Box = $('.theElement');
$('.theElement2').css({ height: Box.height() });
});
// Run on DOM ready
setHeight();
// Run on window resize
$(window).resize(setHeight);
});
Some optimisation hindsight: you might want to consider throttling the resize
event, if many calculations are being performed at the same time. Browsers often fire the event too frequently ;)
Upvotes: 0
Reputation: 104785
Use a resize
event:
$(window).resize(function() {
var Box = $('.theElement');
$('.theElement2').css({ height: Box.height() });
}).resize();
Upvotes: 1