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


Kevin D
Kevin D
8,646 Points

Print out updated variable value in console.log() when browser width changes

Hi all,

Is there a way to update the variable value that is printed in console.log when we update the element.

The scenario:

ā€¢ I'm printing out a variable which takes in the width of a div element

var element_width = $('.some_class').width();

console.log('This is the width value: ' + element_width);

ā€¢ When I resize the screen, the width of the div element changes and I want that change/update to the value to be printed out in the console. This doesn't happen at the moment.

I thought it might be because the code is only run once so I tried placing the console.log() inside a click function so that it would be printed out whenever I clicked on the page. But this is what happens in the console and I can't seem to expand the row (I'm probably doing something stupid!):

Image showing problem user is having

ā€¢ I have tried to manually type into the console the variable to print out the value, but this value doesn't change either.

I'm confident that the div is not a fixed width as I've set it to be width: 90% - so the value should be changing!

Any help would be appreciated!


1 Answer

Hi Kevin,

You're looking for the resize event. Here's how it works in plain JavaScript:

window.addEventListener('resize', function (event) { 
    var width = event.target.innerWidth;
    console.log("Window is now " + width + "px big!!!!");

I'm pretty sure jQuery has a cross-browser compatible wrapper for that event as well ... so if you need to support Internet Explorer or something, I would suggest going down that route.

Kevin D
Kevin D
8,646 Points

Ah cheers! Of course, that makes so much sense!

This is the jQuery .resize() if anyone needs it