Home > Enterprise >  How can I convert this jquery methods - .text(), .height() and .css() to vanilla javascript?
How can I convert this jquery methods - .text(), .height() and .css() to vanilla javascript?

Time:11-05

Hi I hope your having a great day,

Today I decided to try it out to convert from jquery to vanilla javascript on my free time but I've been working this code for hours and I'm really having a hard time on converting this code from Jquery to vanilla javascript.

Code I'd like to change

$("h1").text(Math.round(progress)   "%").css({ color: textColor });    
$(".fill").height(progress   "%").css({ backgroundColor: bgColor });

Full code:

function progress() {
    var windowScrollTop = $(window).scrollTop();
    var docHeight = $(document).height();
    var windowHeight = $(window).height();
    var progress = (windowScrollTop / (docHeight - windowHeight)) * 100;

    var bgColor = progress > 99 ? "#fff" : "#fff";
    var textColor = progress > 99 ? "#fff" : "#333";

    $("h1").text(Math.round(progress)   "%").css({ color: textColor });

    $(".fill").height(progress   "%").css({ backgroundColor: bgColor });
}

progress();

I'm really sorry for all the trouble I hope you could help me with my problem. Thank you.

CodePudding user response:

I think this is what you need

document.querySelector("h1").innerText = Math.round(progress)   "%"
document.querySelector("h1").style.color = textColor
document.querySelector(".fill").style.height = progress   "%"
document.querySelector(".fill").style.backgroundColor = bgColor

Small code snippet here However, there are multiple issues with the snippet considering bad practice.

You should append CSS using a class (helps with iOS). Also, if you want to put this on multiple element with the same class name/tag name, consider using querySelectorAll with a loop inside.

  • Related