move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click?

I tried implementing this code, but unfortunately, it doesn't bring the div back.

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.className = d.className + " move";
});

Answer №1

It's preferable to use

d.classList.toggle("transitionClassName")

I took inspiration for the transitions from this resource on CSS transitions between left -> right and top -> bottom positions

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.classList.toggle("move");
  d.classList.toggle("right");
});
.animate {
  height: 100px;
  width: 100px;
  background-color: #c00;
  transition: all 1s ease;
  position: absolute;
  cursor: pointer;
  font: 13px/100px sans-serif;
  color: white;
  text-align: center;
}


/* ↓ just to position things  */

.animate.left {
  left: 0;
  top: 50%;
  margin-top: -100px;
}

.animate.right {
  right: 0;
  top: 50%;
}

.animate.top {
  top: 0;
  left: 50%;
}

.animate.bottom {
  bottom: 0;
  left: 50%;
  margin-left: -100px;
}

.animate.left.move {
  left: 100%;
  transform: translate(-100%, 0);
}

.animate.right.move {
  right: 100%;
  transform: translate(100%, 0);
}

.animate.top.move {
  top: 100%;
  transform: translate(0, -100%);
}

.animate.bottom.move {
  bottom: 100%;
  transform: translate(0, 100%);
}
<button type="button" id="button" class="animate">Move</button>

Answer №2

const button = document.getElementById("button");

button.style.transition = "1.0s";

button.addEventListener('click', function(event) {
    event.target.classList.toggle("moving");
});
.moving {
  margin-left: 75px;
}
<button id="button">Press Me!</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

How can you employ moment.js to display the most recent update time of mongoDB/mongoose?

I am facing an issue with displaying the last date/time when any entry in my table was edited and updated using moment.js. It seems to be updating the date/time in real-time rather than only showing when a database entry was modified. How can I ensure tha ...

What is causing lxml to not remove section tags?

Having some trouble parsing HTML using lxml and Python. My goal is to eliminate section tags, but seems like lxml can remove other specified tags except for sections. For instance: test_html = '<section> <header> Test header </header& ...

Mastering the use of node cluster mode in conjunction with agenda cronjobs

Currently, I am utilizing nodejs and agenda to run cronjobs. With a total of 10 cronjobs in place, the process is taking longer as nodejs is single-threaded and they all run simultaneously. In an attempt to resolve this issue, I experimented with pm2 by e ...

Extract the HTML content from a file stored on the computer

Currently, I am utilizing Google App Engine alongside Python. My goal is to retrieve the tree structure of an HTML file located within the same project as my Python script. Despite attempting numerous approaches, such as using absolute URLs (for example ht ...

What is preventing me from accessing the props of my functional component in an event handler?

I've encountered a strange issue within one of my components where both props and local state seem to disappear in an event handler function. export default function KeyboardState({layout, children}) { // Setting up local component state const [c ...

Ways to determine if an HTML element contains a child element that is a hyperlink

I need to verify the presence of an object on the page that contains a link. The object is represented as follows: <td > <input class="ng" type="checkbox"/> <a href="http://testsite.com ">67365853</a> </td> Although ...

Is it possible to transfer a specific feature from jQuery to Prototype?

I find myself in a situation where I have to use Prototype instead of jQuery, even though I'm not as familiar with it. Can anyone assist me in transforming the following script: var output={}; $$('ul li').each(function(item){ var firstL ...

Incomplete Website Encryption Alert

Currently, I am developing a website called "usborroe.com" and have just set up a GeoTrust Business ID SSL Certificate. However, despite my efforts to ensure full encryption on the site, an error message is indicating that it is not fully encrypted and t ...

changing background color smoothly in a short time without using JQuery

Check out this link for some code .back { margin: 20px; padding: 100px; background: yellow; font-size: 30px; } <div class="back"> Fun place to stay. We got a golf cart to see the rest of the island, but the ...

What is the best way to arrange an unordered list in a horizontal layout?

I have four lists that I want to display side by side. The first row should show a Doctor and Patient side by side, the second row should show a Pharma Company and Employee side by side. However, in my code, this layout is not working as intended. .tree ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

Place the object into a vacant area with the help of jQuery Sortable

I am using jQuery Sortable and it's functioning well. However, I have encountered a small issue that I need help with.    I have two blocks where elements from one block can be moved to the other. The problem arises when all the elem ...

Changing the click event using jQuery

My JavaScript snippet is displaying a widget on my page, but the links it generates are causing some issues. The links look like this: <a href="#" onclick="somefunction()">Link</a> When these links are clicked, the browser jumps to the top of ...

Ways to eliminate hover effect in CSS

I have a text that is currently displayed as a hyperlink, and some CSS code is causing it to underline and become bold when hovered over. I want to remove the hyperlink, but still keep this style by default without needing to hover over the text. Here is m ...

What is the best way to display HTML content from a stored object?

In my project using Next.js, I am faced with the challenge of rendering custom landing pages based on their unique URLs. While I have successfully retrieved all the necessary details from the database for each specific URL, there is a particular object con ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

Display a loading indicator or progress bar when creating an Excel file using PHPExcel

I am currently using PHPExcel to create excel files. However, some of the files are quite large and it takes a significant amount of time to generate them. During the file generation process, I would like to display a popup with a progress bar or a waitin ...

Tips for organizing a Material UI DataGrid table effectively while keeping the total sum rows within the DataGrid unaffected

Check out my codeSandbox link here: https://codesandbox.io/s/making-sum-of-column-in-datagrid-mui-zjzfq6?file=/demo.js I've noticed that when I sort by ascending, the subtotal, total, and tax rows move up, but when I sort by descending, they move dow ...