Reputation: 324
I have created 2 divs on top of each other. The first div holds a WordPress generated img and the second div slides in from the top when hovering the image div. In the normal css both divs have a fixed height, but when i add media queries i need to change the height of the image div to auto to maintain the right dimensions.
HTML code:
<div class="portfolio-page-thumbnail">
<?php the_post_thumbnail(); ?>
<div class="portfolio-page-hover">
<p>BEKIJK PROJECT</p>
</div>
</div>
CSS:
.portfolio-page-thumbnail{
width: 100%;
height: auto;
}
.portfolio-page-hover{
width: 100%;
position: absolute;
top: -50%;
}
Here is the problem: When decreasing my browser width, the image scales just fine, but the hover div stays at a fixed height and because the hover div has an absolute positioning, it cant inherit the height from it's parent.
I created a jQuery snippet to take the height from the image div and set this height to the hover div.
$(document).ready(function(){
$(".portfolio-page-hover").height( $(".portfolio-page-thumbnail").height() );
});
And this works fine on refresh, but as soon as I decrease my browser width, this no longer applies and I have to refresh again. Normally this is just fine, but when my client changes from portrait to landscape, it appears broken. I'd like to know if there is an solution to set the height 'real time' without refreshing?
Thnx!
Upvotes: 2
Views: 2162
Reputation: 324
Ok, first of all, thnx to all you guys/girls for your help. I found a solution by combining the above answers.
Result:
// Sets the right height to the Hover element
function myFunc() {
$(".portfolio-page-hover").height( $(".portfolio-page-thumbnail").height());
}
//Sets the correct height on refresh
myFunc();
// sets height when resizing the window
$( window ).resize(function() {
myFunc();
});
Note: This code will be placed inside another code that allready has a document.ready function.
Is it written the correct way? Or can the code be cleaner?
Upvotes: 1
Reputation: 22817
I figured I'd turn my comment into an answer. Same answer as Spencer however it calls a function so you don't have to write it multiple times.
$(document).ready(function(){
myFunc();
});
$(window).resize(function(){
myFunc();
});
function myFunc() {
$(".portfolio-page-hover").height( $(".portfolio-page-thumbnail").height());
}
More information about jQuery's resize event handler here
Upvotes: 1
Reputation: 21565
You could place it inside a resize
event handler:
$( window ).resize(function() {
$(".portfolio-page-hover").height( $(".portfolio-page-thumbnail").height());
});
This will get called whenever the window is re-sized.
Upvotes: 8