JSFiddle - React, Tailwind, and code Playground
by Danny_Joris
HTML
<div class="block"></div>
CSS
.block {
float: left;
width: 20px;
height: 200px;
background-color: lightgreen;
}
@media screen and (max-width: 399px){
.block {
background-color: red;
}
}
JavaScript
// Unbinding a function doesn't prevent a delayed function to trigger after unbind.
// The green block is set to half the window size. Moving below 400px width, this functionality is removed/unbound. Though because of a delay in the bound function, it still gets triggered after the function is unbound.
var methods = {
resizeBlock: function() {
var halfwidth = $(window).width() / 2;
// add small delay
setTimeout(function() {
$('.block').width(halfwidth);
}, 300);
console.log('Set width');
}
}
// init
methods.resizeBlock();
// on window resize
$(window).on('resize.block', methods.resizeBlock);
$(window).on('resize.window', function() {
console.log($(this).width());
if ($(this).width() < 400) {
$(window).off('resize.block', methods.resizeBlock);
$('.block').removeAttr('style');
console.log('Unbind and reset');
}
else {
$(window).on('resize.block', methods.resizeBlock);
}
});