EDIT:
I have made a JSFiddle for this... but I don't think it will work right because of (window).resize(); I havn't played with JSFiddle much so I have a feeling I did this wrong.
http://jsfiddle.net/beefchimi/uhw3D/25/
If anyone can help with this problem, I would really appreciate it.
So I have been struggling to find the absolute best way to reproduce CSS Media Queries with jQuery. I use CSS Media Queries almost exclusively when I can, but I'm dealing with a problem right now where I need to be able to calculate a value dynamically and apply it to an element on window resize.
Using the code below, I can check the window width at every 1 pixel increment. Firstly, I wonder if this is good performance wise, and if instead would there be a way to only execute the function when we move from breakpoint to breakpoint (480 / 768 / 1024) rather than every pixel along the way.
My problem is this however:
I am checking to see how many elements in the current layout have the CSS property of left: 0; and then I multiply the number of elements by 240px and apply that as the height value for a container.
Below 720px, the height for this element needs to be 'auto'. This works fine. But if I am going up from 320px, and I hit my first breakpoint (720px), I get the right height applied to my container, but once I hit the breakpoint above that (960px), the height never updates. I am wondering what I am doing wrong that is preventing the new value from being calculated and applied.
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
var elementCount = $('#casestudy-content article').filter(function() { return $(this).position().left === 0 }).length;
if ( windowSize >= 720 && windowSize <= 959 ) {
console.log("Greater than 720 and less than 960");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else if ( windowSize >= 960 && windowSize <= 1199 ) {
console.log("Greater than 960 and less than 1200");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else if ( windowSize >= 1200 ) {
console.log("Greater than or equal to 1200");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else {
$('#casestudy-content').css('height', 'auto');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
Any help would be greatly appreciated.
EDIT
So I discovered that, if I remove CSS transitions on these elements, my function works perfectly.
Interestingly, my console.log(elementCount) reports the correct value the moment I hit the breakpoint, so I would think that should mean I don't have to worry about the transition time, but apparently so. How can I go about delaying this function so that I can keep the transitions? If my transitions take 0.2s, I need to delay my function from firing by that much. Any help on this?