Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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!

Thanks

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

Thanks!