Search code examples
javascriptcssclip

Change clip in CSS with JS


So I'm making an HP bar and I need to shorten the width of the HP bar when the remainingHealth is decreasing. So far I've written this.

JS

var remainingHealth =333;
function update(){
    document.getElementById("nowbar").style.clip = "rect(0, remainingHealth, 90, 0)";
}

CSS

#nowbar {
    position: absolute;
    margin-top: -24px;
    margin-left: 5px;
    clip: rect(0px,666px,90px,0px)
}

I created an image to explain what the problem is: https://i.sstatic.net/bgWV8.png

So the problem is that I can't control the width with JS so on the screen the width is showing 666px instead of remainingHealth(333px). But when I change remaininingHealth with 333 in the style.clip it's displaying 333px so it's working.


Solution

  • So there is a little confusion in how you are looking at this I think.

    So when you write the javascript code:

    var remainingHealth =333;
    

    The var remainingHealth does equal 333. It does not equal 666 or is any way connected to the CSS file as you seem to be implying in your pic: https://i.sstatic.net/bgWV8.png

    The problem is that

    document.getElementById("nowbar").style.clip
    

    requires a string value, you are giving it a string value too, the string value you are setting document.getElementById("nowbar").style.clip to is:

    "rect(0, remainingHealth, 90, 0)"
    

    That is the same as if doing in your CSS file:

        #nowbar {
        position: absolute;
        margin-top: -24px;
        margin-left: 5px;
        clip: rect(0, remainingHealth, 90, 0);
        }
    

    You can see that "remainingHealth" is not valid CSS, remainingHealth is a string in your javascript code is what I am trying to show you, it is not the var remainingHealth that you set to the integer value of 333.

    You need to do:

    document.getElementById("nowbar").style.clip = "rect(0," + remainingHealth + "px, 90, 0)";
    

    Javascript is "kind" enough to convert the int var remainingHealth to the string value "333" for your string concatenation.