Reputation: 2048
I have a function which resizes thumbnails on a page:
function adjustThumbs(){
if ($(window).width()<900) {
var w = ($("#wrapper").width())/2;
}
else if ($(window).width()>900 && $(window).width()<1100){
var w = ($("#wrapper").width())/3;
}
else if ($(window).width()>1100 && $(window).width()<1680){
var w = ($("#wrapper").width())/4;
}
else if ($(window).width()>1680 && $(window).width()<2300){
var w = ($("#wrapper").width())/5;
}
else if ($(window).width()>2300){
var w = ($("#wrapper").width())/6;
}
$(".tableMaker, .imgContainer").each(function(){ $(this).css("width", w); });
$(".debug").text("debug = "+w);
}
Once the page has loaded, I fire the function.
It doesnt do what it should.
But on resize, it does?
I have a debug div in the top middle of the page which shows me that on page load, if the browser is full screen (1440 wide on my macbook pro), w = 335, but if i move it just a pixel, it jumps to 331.25, which is a 3.75px discrepancy.
The point is... is that when i call the function the second time, it does work... so why would it not work first time?
My scripts are all at the bottom of the page, and everything is on document ready.
Thanks
Upvotes: 0
Views: 153
Reputation: 28097
Maybe the discrepancy is the difference between the page being loaded and the page being ready. It may also be a browser issue as the difference between the first function run on document ready
and me resizing my browser a pixel afterwards is fine.
You should try triggering the window resize event instead of calling the function inline. To trigger the resize event, you can tag it on the end after you've bound the event like so:
$(window).resize(function(){ adjustThumbs(); }).resize();
Upvotes: 1
Reputation: 6605
in general i wouldn't assign partial pixels, but round them beforehand.
found a bug in your code, but most likely not related. you're checking always "<" and ">" so w will be undefined in case the window width is exactly 900, 1100, 1680 or 2300 pixels
another note: calculate $(window).width() only once and store it in a variable. it's not necessary (and heavy) to call it 8 times (worse case)
just my 2 cents
Upvotes: 0