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();
});
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.