The object is not moving on clicking the button. Why is it so?
function animate() {
var object = document.getElementById('object').style;
var x = 100;
object.left = x + 'px';
}
#object {
position: absolute;
top: 50px;
right: 20px;
left: 20px;
height: 40px;
width: 80px;
background-color: green;
}
If we assume that your element with the object
id is the button, then all you need to do is attach an event listener to it so that the animate
function is called when you click it.
const object = document.getElementById('object');
object.addEventListener('click', animate, false);
Now we just need to rewrite your animate
function so that it moves the element associated with the click.
function animate() {
var x = 100;
this.style.left = x + 'px';
}
If you don't want your button to be that object, add a button to the HTML:
<button id="button">Click me</button>
then add the event listener to the button:
const button = document.getElementById('button');
button.addEventListener('click', animate, false);
And then revert your animate
function back to the way it was. Here I've captured the element only in the object
variable, as it makes more sense with the variable name you're using.
function animate() {
const object = document.getElementById('object');
var x = 100;
object.style.left = x + 'px';
}
Note: if the browsers with which you're working support template literals the last line of your animate
function can be:
object.style.left = `${x}px`;