0

Can this jQuery window load script be converted into pure javascript? I was wrong, I didn't dive into pure javascript before learning about jQuery.

can you i convert this jquery to pure javascript?

This is my code

$(window).load(function () {
    $("#loading").fadeOut("fast");
});
$(window).on("beforeunload", function () {
    $("#loading").fadeIn("fast").delay(1000).show();
});
vhlan
  • 1
  • 2
  • welcome to the community... https://stackoverflow.com/questions/2304941/what-is-the-non-jquery-equivalent-of-document-ready https://stackoverflow.com/questions/36532467/window-bindload-and-element-html-in-pure-javascript – Gabriela Dec 09 '20 at 00:04
  • http://youmightnotneedjquery.com might be helpful. – Nathan Chu Dec 09 '20 at 00:07

1 Answers1

0

The load function can be replaced with onload (scrapping the window because onload is already a global variable) and the $ jquery query selector function is the same as document.querySelector. The on function is equivalent to the addEventListener function.

The pure js code is

onload = function () {
    const elem = document.querySelector("#loading");
    var opacity = 1;
    var timer = setInterval(() => {
      opacity -= 50 / 400;
      if( opacity <= 0 )
      {
        clearInterval(timer);
        opacity = 0;
        elem.style.display = "none";
        elem.style.visibility = "hidden";
      }
      elem.style.opacity = opacity;
      elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
    }, 50); // this part is from https://stackoverflow.com/questions/13733912/javascript-fade-in-fade-out-without-jquery-and-css3
};
addEventListener("beforeunload", function () {
    const elem = document.querySelector("#loading");
    elem.style.opacity = 0;
    elem.style.filter = "alpha(opacity=0)";
    elem.style.display = "inline-block";
    elem.style.visibility = "visible";
    var opacity = 0;
    var timer = setInterval( function() {
      opacity += 50 / 400;
      if( opacity >= 1 )
      {
        clearInterval(timer);
        opacity = 1;
      }
      elem.style.opacity = opacity;
      elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
    }, 50 ); // this part is also from https://stackoverflow.com/questions/13733912/javascript-fade-in-fade-out-without-jquery-and-css3
    setTimeout(()=>{elem.style.display="block";},1000);
});

this all should match up to what jquery would do but something could always go wrong.

Timothy Chen
  • 431
  • 3
  • 8