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

What could be the reason for the email not being displayed in the form?

I am attempting to automatically populate the user's email in a form when a button is clicked, preferably when the page is loaded. However, I am encountering issues with this process. This project is being developed using Google Apps Script. Code.gs ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

Guide on adding the contents of non-empty <td> tags using Javascript or JQuery

My goal is to calculate the total sum of all the HTML content within <td> elements with the attribute name='gross_val'. Here are the <td> elements I am working with: <tr><td name="gross_val" align="right" title="gross_val1" ...

Is it possible for jquery JSON AJAX to block all users?

On my website, I use AJAX to load an RSS feed on the client side when the page loads. If a user repeatedly presses F5, could the owner of the RSS feed ban my entire website instead of just that one user? This would prevent others from loading the RSS feed ...

Updating the chosen option using jQuery

Is there a way to change the currently selected option using jQuery? <select name="nameSelect" id="idSelect"> <option value="0">Text0</option> <option value="1">Text1</option> <option value="2" selected>Text ...

Alter information exclusively when the user is actively viewing my webpage

It's funny how Facebook used a similar technique in the past, Imagine you opened facebook.com, scrolled through your feed for a bit and then decided to open a new tab to read some news. Even though there were updates on your Facebook feed while you w ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...

AngularJS uses double curly braces, also known as Mustache notation, to display

I'm currently working on a project where I need to display an unordered list populated from a JSON endpoint. Although I am able to fetch the dictionary correctly from the endpoint, I seem to be facing issues with mustache notation as it's renderi ...

Attempting to save MongoDB data into a variable for integration with Handlebars.js

Having an issue with storing MongoDB data in a variable to display in HTML using hbs. The specific error message is TypeError: Cannot read property 'collection' of undefined. Here's the code snippet I have written: const express = require(& ...

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

Tips for safeguarding the security of my PHP API when accessed through Ajax using OAuth2

I've developed a cross-origin ajax application that utilizes some personal APIs I created. Now, I'm looking to enhance the security measures so only my application has access to the API. After researching, I came across OAuth2 at OAuth2. I foll ...

Error: Unable to assign value to the innerHTML property of an undefined element created by JavaScript

When designing my html form, I encountered an issue where I needed to display a message beneath blank fields when users did not fill them out. Initially, I used empty spans in the html code to hold potential error messages, which worked well. However, I de ...

Choose a specific portion of text following an element in HTML using CSS

I would like to style the text following the span tag using CSS without affecting the span tag itself. Specifically, I want to apply styling only to the text that reads "Text to be selected", leaving the span tag unaffected. The style I desire i ...

Retrieve index by clicking on a mapped array in a React.js application

class DataCard extends React.Component { constructor(props){ super(props) this.state = { show: false, } } displayContent = (e) => { e.preventDefault(); console.log(e.target.entry); } render() { console.log(this.props ...

When incorporating reduce into your code, remember to expect an undefined

Imagine you have an array like this: const novels = [ { id: 1, name: 'The Da Vinci Code', genre: 'Mystery', author: { name: 'Dan Brown', birthYear: 1964, }, releaseYear: 2003, }, { ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

How to use PHP for setting up a MySQL database?

Currently, I am immersing myself in the world of PHP and MySQL. I decided to take a shot at creating a basic HTML form along with a PHP script to set up a MySQL database. Unfortunately, when I tried to test it out, things didn't go as planned. Upon su ...

Embedding a PDF file into an HTML form

For days, I have been on a relentless search for a solution to my problem to no avail. My ideal scenario involves embedding a fillable pdf form into an intranet html form for submission to the server, with the ability to parse field/values being a bonus b ...

The height on iPad Chrome is displaying incorrectly

iPad Pro(11-inch), iPadOS version: 16.6.1, Chrome version: 116.0.5845.177 I tried running a simple html file on my iPad and encountered an issue. Despite setting the height to 100vh, a vertical scrollbar appeared on the right side of the screen allowing ...