I failed to use on-click functions in javascript. How can I add fade-in class on-click event? If possible modern javascript use or es6. Also, how can I remove the class in 5 seconds? Please suggest me no JQuery.
If possible all click event method function use.
I failed to use on-click functions in javascript. How can I add fade-in class on-click event? If possible modern javascript use or es6.Also, how can I remove the class in 5 seconds? Please suggest me no JQuery, please. if possible all click event method function use.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>css layout</title>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
@-webkit-keyframes fadeIn {
to {
opacity: 1;
}
}
@keyframes fadeIn {
to {
opacity: 1;
}
}
.fade-in {
-webkit-animation: fadeIn .5s ease-in 1 forwards;
animation: fadeIn .5s ease-in 1 forwards;
opacity: 0;
}
</style>
</head>
<body>
<!--button-->
<p>
<button onclick="animations()">Click Me</button>
</p>
<div id="container">
<div id="animate"></div>
</div>
<!--js-->
<script>
function animations() {
var elem = document.getElementById("animate");
}
</script>
</body>
</html>
You could add a class to a DOM element using the classList
property.
See the MDN entry for classList
: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
You could then remove the class using a setTimeout function.
So your animation function could look something like this:
function animations() {
var elem = document.getElementById("animate");
elem.classList.add('fade-in'); // Add .fade-in class
setTimeout(function() {
elem.classList.remove('fade-in'); // Remove .fade-in class
}, 5000); // 5000ms
}