Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance.

My goal was to create a div that moves back and forth using toggleClass;

$('div').on('click', function() {
    $(this).toggleClass('active');
});

as well as keyframes;

.active {
    animation-name: moveme;
    animation-duration: 1s;
    animation-timing-function: linear;
    animation-fill-mode: forwards;
}

@keyframes moveme {
    0%  {transform: translate(0,0)}
    50%  {transform: translate(-200px, 0px)}
    100%  {transform: translate(-200px,-50px);}
}

However, when the div returns to its original position, it does not animate. I would like the div to animate in reverse with the same animation. Is there a way to achieve this?

You can view what I'm attempting to do here jsfiddle.net/jmrMW/43/ The example is simple now, but it will become more complex in the future.

Thank you kindly for your help! ^^

Answer №1

When it comes to manipulating classes in Javascript, the effects can be instant. However, if your CSS animations are only bound to the .active class, clicking a second time can cause you to lose that class and therefore lose the animation effect.

Instead of duplicating code like others have suggested, let's think like true programmers and utilize the power of CSS3 animations. Why not try a different approach by setting animation-direction: alternate and animation-play-state: paused, then defining a CSS class for movement:

.moving {
  animation-play-state: running;
}

Next, apply this class to the element for just 1 second after it has been clicked:

var $moveable = $( '.moveable' ).eq( 0 );

$moveable.click(function() {
    $moveable.addClass( 'moving' );
    setTimeout(function() {
         $moveable.removeClass( 'moving' );
    }, 1000);
});

Take a look at this fiddle for a demo.

Update

This solution does have a drawback - using timers in both JS and CSS may not sync perfectly. The animation becomes infinite, going slightly further each cycle. To fix this, we can increment animation-iteration-count to prevent it from proceeding to the next cycle. Still fun experimenting though!

Check out this updated fiddle for more details.

Answer №2

I have created a modified version of your JSFiddle code. I essentially replicated the keyframes you already had but implemented them in reverse for a different effect. Feel free to check it out!

$('div').on('click', function() {
  if ( $(this).hasClass("go-up") ) {
    $(this).removeClass("go-up").addClass("go-down");
  } else {
    $(this).addClass("go-up").removeClass("go-down');
  }
});
div{
  background:#aaa;
  width: 200px;
  margin: 20vh auto;
  height: 200px;
}
.go-up {
  animation-name: moveup;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-delay: 0s;
  animation-fill-mode: forwards;
}
.go-down {
  animation-name: movedown;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-delay: 0s;
  animation-fill-mode: forwards;
}

@keyframes moveup {
  0%  {transform: translate(0,0)}
  50%  {transform: translate(-100px, 0px)}
  100%  {transform: translate(-100px,-50px);}
}

@keyframes movedown {
  0%  {transform: translate(-100px,-50px);}
  50%  {transform: translate(-100px, 0px)}
  100%  {transform: translate(0,0)}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div></div>

Check out the modified version here.

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

When using Vue.js, binding may not function properly if it is updated using jQuery

Link to JsFiddle Below is the HTML code: <div id="testVue"> <input id="test" v-model="testModel"/> <button @click="clickMe()">Click me</button> <button @click="showValue()">Show value</button> </div& ...

Effective ways to transfer data between services and controllers

Is there a way to pass values from services to controllers effectively? Despite researching on stackoverflow, I haven't found a solution that addresses my issue. My goal is to access google spreadsheets using tabletop.js. Interestingly, when I log val ...

Having trouble getting the dropdown button to function properly in my Bootstrap navigation bar implementation

Can anyone help me troubleshoot why the dropdown button is not functioning in my code? I've tried following tutorials and searching for solutions online, but nothing seems to work. Any assistance would be greatly appreciated. <!DOCTYPE html> & ...

Click the button to access the login form created using React components

I have been working on developing a login form that includes various input components and a button component. SignIn.js class SignIn extends Component { render() { return ( <article className="br2 ba dark-gray b--black-10 mv4 w-100 w-50-m ...

Firefox 3.5: The Notorious Code Copycat

Encountering an issue in Firefox 3.5.2 where after clicking a link on the page and then returning using the back button or another link, extra HTML code appears. Unsure if it's added by Firefox or related to PHP code. Unfortunately, unable to share t ...

JQuery fails to remove the "display:hidden" attribute

List of methods I attempted: Utilizing .removeClass and addClass functions Applying show() and hide() methods Modifying the CSS properties Initially, I confirmed that my script contains onLoad. Furthermore, all other elements are functioning correctly. D ...

Sending data through AJAX

I am currently working on a calendar project. I want to include a description box next to the calendar, where additional information about an event will be displayed when a user clicks on a specific date. Here is what I have so far in terms of HTML/PHP: ...

Adaptive web layout (Adjusting design based on screen size)

I'm feeling a bit confused about responsive web design. I understand that I can use media queries to apply different stylesheets based on specific screen sizes. For example, a screen at 600px will use one stylesheet while a larger screen will use a co ...

Verify the presence of plain ASCII text

I need to verify if the file uploaded is in ascii plain text format. Can you suggest a method? $("#my_file").change(function(){ //alert if file is not ascii plain text }); <input type="file" name="my_file" id="my_file" /> ...

What causes my useEffect hook to trigger twice in React?

I'm currently utilizing @preact/signals-react in my react project for integration purposes. Encountered a challenge that requires resolution. Interestingly, I discovered that by removing import { signal } from '@preact/signals-react', the ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

What is the best way to delete a nested document within an array in MongoDB by referencing its _id?

I am trying to remove a nested object from an array of objects called createdEvents if the createdEventId matches the id I pass to it. This is the JavaScript query I am using: db.collection("users").updateOne({ _id: userId }, { $pull: { createdEv ...

The CSS file is not displaying the background image on the PHP file

I am facing an issue with using CSS to include a background image for the layer, but it doesn't seem to be working correctly... The CSS code snippet is as follows: header { background-image: url("boisko.jpg"); background-repeat: no-repeat; background ...

What is the process for accessing and modifying cookies in a local file:/// HTML document?

What is the most effective method for reading/writing cookies in a local file:/// HTML document using JavaScript or jQuery? I attempted the following: function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate( ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

What could be the reason for data-id coming back as undefined?

I'm having trouble figuring out why the code below isn't working for me. The console is showing 'undefined' for data-id. href='#detailsModal' class='btn btn-info btn-xs' data-toggle='modal' data-id='x ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Retrieve various elements using a loop and dynamic identifiers (perhaps within a multi-dimensional array)

Apologies for the confusing title. I am currently working on a piece of code which can be found here: https://jsfiddle.net/8ers54s9/13/ This code creates a basic text area and compares it to a predefined array to identify common words within a string. If ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Animation for Images in Angular v1.2

After reviewing tutorials and previous questions, I have been trying to pinpoint where my code is going wrong in applying an animation to transition between the images I want to display. The ng-show function effectively displays the selected picture, but ...