The object is not moving on clicking the button. Why is it so?
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';
}
DEMO
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';
}
DEMO
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`;
You would need to include the styling at the end of the statement
function animate() {
var x = 100;
var object = document.getElementById('object').style.left = x + 'px';
}
#object {
position: absolute;
top: 50px;
right: 20px;
left: 20px;
height: 40px;
width: 80px;
background-color: green;
}
You should not detach style object from DOM element. Also the name of your function conflicts with native Element.animate function, name your function diffrently.
This should work:
function animateX() {
var object = document.getElementById('object');
var x = 100;
object.style.left = x + 'px';
}
#object {
position: absolute;
top: 50px;
right: 20px;
left: 20px;
height: 40px;
width: 80px;
background-color: green;
}
<div id="object" onclick="animateX()"></div>