In this blog post, you will learn how to move a div element with a mouse click in JavaScript.
We can do it by ‘EventListener’ and some other function.
Move a div element with a mouse click in JavaScript.
let’s understand it with an explanation.
<script> document.addEventListener('DOMContentLoaded', function() { //rest of the code }) </script>
This ” document.addEventListener(‘DOMContentLoaded’, function() { “ function waits until the DOM/HTML page gets fully loaded, all the other functions of the code come under this function, so they get executed after the page loaded.
let move=document.querySelector('#move');
this line selects the html div element and assigns it to the verbal ‘move’.
.pg_move{ position: relative; left: 500px; }
here we make a CSS class ‘.pg_move’ with ‘position: relative;’ and ‘left: 500px;’. so, the element moves 500pixcl to the left side.
bt.addEventListener('click',function(){ move.classList.add("pg_move") })
this function add the CSS class ‘.pg_move’ to the div element refence by the variable ‘move’ on the click of mouse.
Full JavaScript code is here.
<script> document.addEventListener('DOMContentLoaded', function() { let move=document.querySelector('#move'); let bt=document.querySelector('#bt'); bt.addEventListener('click',function(){ move.classList.add("pg_move") }) }) </script>
Check it out here:
Click Here