Animate on click with Javascript!
Subhransu Patra
Posted on December 25, 2021
<p>Hello</p>
<p>Merry Christmas</p>
Previous Chapter Chapter 2 (Part 2)
Inform Our World Link here
Animation with js? Not too much tough but if you are new to javascript, like me, then at first it would be a little bit difficult but with time, you would be coping up with it. So, lets start the topic of 'Animate on click with Javascript!'
First create a HTML file...
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate on click with Javascript!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
}
</style>
</head>
<body>
</body>
</html>
Then add any tag such as <a>
or <p>
. It is upto you which tag you will use to animate...
<p>Hello World!</p>
Here I used <p>
tag. Then create an id=""
for it. Let's name it animate. You can use anything...
<p id="animate">Hello World!</p>
Then we need a button so that if we clicked on it, it would animate as per our needs...
<button>Click to Animate</button>
then in the <button>
tag add onclick=""
. It is very much essential for onclick animation.
<button onclick="beyblade()">Click to Animate</button>
I have put beyblade()
in onclick=""
. ()
is very much essential...
Then add <script>
in the body...
<script>
</script>
and in that add
<script>
function beyblade() {
}
</script>
The text after function
will be the one you have written in onclick=""
i.e. I have written onclick="beyblade()"
, the same I will write after function
i.e.
function beyblade() {
}
So, let's take the element that we take be x
. So to do this, implement..
<script>
function beyblade() {
let x = document.getElementById("animate")
}
</script>
then add the following component...
<script>
function beyblade() {
let x = document.getElementById("animate")
x.style.marginLeft = "300px"
x.style.transition = "1s"
}
</script>
x.style.transition
will create transitions and 1s
will create timing for it.
You can implement any css component in place of marginLeft
such as x.style.color = red
it will change the text color to red and x.style.backgroundColor = blue
will change the background color to blue.
It helps us to create a hamburger menu also.
So, this is for today. I hope you liked the article and if you, then please notify me.
Full Code..
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate on click with Javascript!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<p id="animate">Hello World!</p>
<button onclick="beyblade()">Click to Animate</button>
<script>
function beyblade() {
let x = document.getElementById("animate")
x.style.marginLeft = "300px"
x.style.transition = "1s"
}
</script>
</body>
</html>
Thanks for your time. 😺
Posted on December 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 8, 2024