+ 5

How to make a div box move left/right/top/bottom using onclick event?

I tried to use document.getElementById("something").style.left=some number but it doesn't work.

12th Jan 2019, 8:30 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
9 odpowiedzi
+ 10
Hey Alex.You are going the right way .The reason it doesnt work is propably because you didnt add 'position :relative' in the CSS of your div . The div tag wont move without position attribute.
12th Jan 2019, 9:31 AM
Mitali
Mitali - avatar
+ 8
Hey Alex. It is really simple. What you have to do is create a div in html and give it some unique id. Now give it some styling and also create animation for it by using @keyframes. Now create a button with onclick event. And create a function in js part in which you can actually apply that animations to your div. https://code.sololearn.com/W8ru5CA8R920/?ref=app
12th Jan 2019, 9:02 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 8
Raj Chhatrala☑️ I appreciate your way. But it makes the button work only once. Once the animation is performed the button becomes useless. You cannot perform the animation again.
12th Jan 2019, 9:33 AM
Mitali
Mitali - avatar
+ 4
Oh, I forgot about position:relative; maybe that is why it was not working. 😅 Thank you!
12th Jan 2019, 9:59 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 3
Mitali I noticed it now. That's a big bug, I will find a way to perform it again and again.
12th Jan 2019, 9:51 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 3
https://code.sololearn.com/WRu3347N21vD/?ref=app I am not sure why it is not working.
12th Jan 2019, 10:17 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 2
💧Alex Tusinean🔥 It dont works because you have to set the left value more the units (like px) in string. Try to set the value like '100px'
12th Jan 2019, 11:06 AM
KrOW
KrOW - avatar
- 1
I made few changes here, take a look var n=0; function k(){ if(n%2==0) {document.getElementById("diverta").style.left="100px" ; n++;} else{ document.getElementById("diverta").style.left="0" ; n--; } } function right(){ setInterval(k(),10); }
13th Jan 2019, 5:07 AM
Reyot Mhz
Reyot Mhz - avatar
- 1
What if I want it to be working each time I click on it
14th Dec 2021, 4:11 PM
Richies
Richies - avatar