Reputation: 8457
Depending on the user's screen width, if the image is less than 220px, I want the class of mobile
to be added to the h3. It works fine by itself but I also want it to work well with window resizing. So if I resize my browser window, it would automatically add the class if the image width becomes less than 220px. I wrote this code below but I can't figure out what is wrong. When I resize the window, the class does not get added. When I refresh, the class is added, however.
var thumbWidth = $('article.project > img').outerWidth();
function adjustTitle() {
if (thumbWidth <= 220) {
$('.overlay > h3').addClass('mobile');
}
}
$(window).on('resize', function() {
adjustTitle();
});
Upvotes: 1
Views: 129
Reputation: 337733
You need to check the width of the img
inside the adjustTitle()
function so that it is read after the window is resized. Your current code only reads it on load, so the value is never seen to change in your JS. Try this:
function adjustTitle() {
if ($('article.project > img').outerWidth() <= 220) {
$('.overlay > h3').addClass('mobile');
}
}
$(window).on('resize', adjustTitle);
Upvotes: 3