Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Daniel Barone
1,630 PointsjQuery Question - How do I run a function every time my webpage window is resized?
My Code: http://i.imgur.com/WUAnalC.png I know how to run a function every time the window is scrolled:
$(window).scroll(function(){ randomFunction(); });
I tried replacing "scroll" with "resize" but no luck:
$(window).resize(function(){ randomFunction(); });
Is there anyway way to do this?
UPDATE: So I checked jquery API and i'm almost certain this is the right way to do something like this. Does anyone have any ideas as to why my function isn't firing when the window is resized?
1 Answer
Petros Sordinas
16,181 PointsDaniel,
$(window).resize(function()) works (I just tested it on the console in Chrome). Can you share what you tried that didn't work?
Daniel Barone
1,630 PointsPetros Sordinas
16,181 PointsYou should be getting the "window width change" string in the console, correct? What I'm seeing is a logic problem. You calculate windowMinusLogoOver2 once when the document is loaded and then execute windowMarginLeft() on window resize with the same values. Try moving the variable assignments within the windowMarginLeft() function. If I understand what you are trying to do correctly, you want these variables re calculated every time the window is resized.
Daniel Barone
1,630 PointsYep that worked, thanks!
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsHi Daniel,
Do you have an example of where you're trying to use the
resizeevent? Another question I have is are you trying to make it work on a PC, tablet or mobile device?