Anamed
Anamed

Reputation: 109

How to contol a CSS property with Javascript

Ok so i have one div and inside it a canvas: my html file:

<div id="container">
        <canvas id="game" width="600px" height="2000px">
</div>

my css file:

#game{
background: -moz-linear-gradient(top, #00b7ea0%, #008793 14%, #04b9b 43%, #1f00ea 74%, #008793 89%, #009ec3 100%);
bottom: 0px;
position: absolute;    
}
#container{
position: relative;
width:600px;
height:500px;    
}

And here is my question: What code should be used in a javascript file, if i want to control the bottom property of #game?

What i mean i that i want the user to press a botton, e.g. W(=87), and the bottom property to change negative or possitive direction is irrelevant, the need is to make a code that when a key is pressed the magnitude of the bottom property will change.

I hope that i described the probel well, if more info is needed please ask... Looking forward for a reply :-)

Upvotes: 0

Views: 102

Answers (2)

pwdst
pwdst

Reputation: 13735

If you want to set the bottom property dynamically you can do this as follows-

function setHeight (bottomValue) {
    if (typeof bottomValue === "number") {
        bottomValue = bottomValue + "px";
    }

    var gameElement = document.getElementById("game");

    if (gameElement) {
        gameElement.style.bottom = bottomValue;
    }
}

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

Alternatively using jQuery-

$('#game').css('bottom', bottomValue);

See http://api.jquery.com/css/

Upvotes: 1

Steve
Steve

Reputation: 86

Using jQuery you could add the following code to your key press handler:

var newBottomValue = 13;
$("#game").css("bottom", newBottomValue);

If you are not using jQuery I would do something like:

var newBottomValue = 13;
document.getElementById("game").style.bottom = newBottomValue + "px";

Upvotes: 1

Related Questions