Joppieb Joppieb - 1 month ago 7
Javascript Question

combine load and resize plain JavaScript

I combine the load en the resize function in one.

$(window).on("resize", function () {
if (window.innerWidth < 700) {
alert('hello');
}
}).resize();


But I am looking for a code in plain JavaScript (without jQuery).

How can I create this?

Answer

You can do this by adding event listener and calling a function on resize:

window.addEventListener("resize", onResizeFunction);

function onResizeFunction (){
//do whatever you want to do on resize event 
}

Same thing is for onLoad event:

window.addEventListener("load", onLoadFunction);

function onLoadFunction(){
//do the magic you want 
}

If you want to trigger function on resize, when the window loads

window.addEventListener("load", onLoadFunction);

function onLoadFunction(){
//do the magic you want 
onResizeFunction();// if you want to trigger resize function immediately, call it 

window.addEventListener("resize", onResizeFunction);
}

function onResizeFunction (){
//do whatever you want to do on resize event 
}
Comments