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

JavaScript

listening to css change with javascript

Hello Currently Iam trying to find a way that everytime when a css change happens to a html element to fire a script. My problem is so far, I havent found any way to add a listener that fires my script. I simply cant make the listener watch for css changes.

Can you explain a little more about what you mean by css changes? Are these changes happening after interaction with an element?

Basically I currently have a div element and child canvas element. Everytime when the size of the div changes, by media queries, I want to have a script that watches the div size and once the div size changes, to change the canvas size too. Also by typing this I just found the answer too my problem. I can just use media queries to change the canvas size too. Opps. Even though my problem is kinda solved iam still curious. How could I watch a css change, caused by media queries, to automatically fire a script?

2 Answers

Steven Parker
Steven Parker
243,318 Points

:point_right: You can create a MediaQueryList object using the window.matchMedia() function. You can then add event listeners to that object.

It's not listening directly to the CSS, but it is listening to the same media changes that the CSS is.

But for your current needs, I agree that simply adjusting the canvas size via CSS is a better solution.

ohh never heard of that one! Was very sure something like this existst just hadnt found it yet, many thanks :)

You could also look up Foundation and Bootstrap and how you can add multiple sizes to your grid based on screen size.

so for instance you could do class="col-md-4 col-sm-6 col-lrg-2" etc.....