Matt104
Matt104

Reputation: 79

Changing background position with Javascript?

Though I can see this question has been asked before I really need a solution without the use of JQuery, its for an embedded web interface and I don't want the overhead of loading jQuery. I need to be able to manipulate sprites using just the JS on the single page, the state of the sprite is dependent on certain JS variables. I'm sure this must be possible, but can't find anything without the use of JQuery.

Upvotes: 3

Views: 16908

Answers (2)

Mujtaba Hassan
Mujtaba Hassan

Reputation: 2493

The easiest way (I think) is to define your own css classes and change those clasess on certan events. i.e.

<style type="text/css">
.bg1{
/* Some attributes set here */
background-position:cen‌​ter;
}
.bg2{
/* Some attributes set here */
background-position:left;
}

</style>

and then you put your javascript like this

document.getElementById("some_id").class = "bg2";

Upvotes: 4

Asraful
Asraful

Reputation: 1290

I think you can use Object.style.backgroundPosition="position" to change your desired background position .

Try this code

 <!DOCTYPE html>
<html>
<head>
<style>
div
{
background-image: url('example.png');
background-repeat: no-repeat;
width: 400px;
height: 400px;
border: 1px solid #000000;
}
</style>
<script>
function displayResult()
{
document.getElementById("div1").style.backgroundPosition="center bottom";  
}
</script>
</head>
<body>

<button type="button" onclick="displayResult()">Position background image</button>
<br>
<div id="div1">
</div>

</body>
</html>

Reference

Upvotes: 4

Related Questions