Reputation: 2191
I'm trying to make my simple javascript function (no jQuery) log a message to the console when the browser is resized to over or under 890px. This code works on load, but only states the starting width when the page is loaded:
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
But my code below using a window event doesn't work:
if (window.attachEvent) {
window.attachEvent('onresize', function() {
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
})};
Can someone explain what I'm doing wrong here? I'm relatively new to javascript. Thanks for any help here.
Upvotes: 0
Views: 98
Reputation:
const on = (e, i, t = window) => typeof t.addEventListener === 'function'
? t.addEventListener (e, i)
: t.attachEvent ('on' + e, i)
const test = () => console.log (window.innerWidth < 890 ? '< 890' : '>= 890')
on ('resize', test)
Upvotes: 0
Reputation: 11
Just try the following code
window.onresize = resize;
function resize()
{
if(document.body.clientWidth < 890)
{
alert("resize event detected!");
}
}
Upvotes: 0
Reputation: 28475
onresize
is to be used as an attribute in your html. e.g. <body onresize="resizePage()"></body>
The correct event is resize
. Try following
if (window.attachEvent) {
window.attachEvent('resize', function() {
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
})
}
Please note, you can also consider using addEventListener
. For details, refer to another answer here
Upvotes: 1
Reputation: 1996
try this
if(window.attachEvent) {
window.attachEvent('onresize', function() {
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
});
}
else if(window.addEventListener) {
window.addEventListener('resize', function() {
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
}, true);
}
else {
console.log('browser does not support Javascript event binding');
}
Upvotes: 1
Reputation: 94
window.addEventListener('resize', () => {
if (window.innerWidth < 890) {
console.log('Less than 890px');
} else {
console.log('890px or more');
}
});
Upvotes: 3