Unlock the power of toggling CSS transitions with just one JavaScript event!

I am facing difficulty in adjusting elements that require transitions at times and not at other times.

The individual actions work fine but when combined, the view does not update properly halfway through. What could be a possible solution?

$(document).ready(function() {
  $('#goLeft').on('click',function() {
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
  });
  $('#goRight').on('click',function() {
    $('#box').addClass('soft');
    $('#box').css('left','400px');
  });
  $('#goLeftAndRight').on('click',function() {
    //copy
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
    //Need for timeout?
    //copy
    $('#box').addClass('soft');
    $('#box').css('left','400px');    
  });
});
h2 {
  cursor:pointer;
}

#box {
  position: fixed;
  top:100px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

#box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.soft {
  transition: all 0.3s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <h2 id="goLeft">jump left</h2>
    <h2 id="goRight">slide right</h2>
    <h2 id="goLeftAndRight">jump left and slide right</h2>
    <div id="box"><p>use headers to move</div>
  </body>
</html>
      

Answer №1

There are two methods to accomplish this task:

1. - Integrating your function with CSS animation

$(document).ready(function() {
  $('#goLeft').on('click', function() {
    $('#box').removeClass('soft left-right');
    $('#box').css('left', '300px');
  });
  $('#goRight').on('click', function() {
    $('#box').addClass('soft').removeClass('left-right');
    $('#box').css('left', '400px');
  });
  $('#goLeftAndRight').on('click', function() {
    $('#box').addClass('left-right').removeClass('soft');
  });
});
h2 {
  cursor: pointer;
}

#box {
  position: fixed;
  top: 100px;
  left: 400px;
  height: 100px;
  width: 100px;
  background-color: #358;
}

#box p {
  padding: 5px;
  color: #fff;
  text-align: center;
}

.soft {
  transition: all 0.3s ease-out;
}
@keyframes leftRight{
  0%{left:300px}
  100%{left:400px}
}

.left-right{
  left:400px
  animation: leftRight 0.3s forwards ease-in-out;
  -webkit-animation: leftRight 0.3s forwards ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <h2 id="goLeft">jump left</h2>
  <h2 id="goRight">slide right>/h2<
  <h2 id="goLeftAndRight">jump left and slide right</h2>
  <div id="box">
    <p>use headers to move</div>
</body>

</html>

2. - Incorporating your function with the setTimeout function.

$(document).ready(function() {
  $('#goLeft').on('click',function() {
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
  });
  $('#goRight').on('click',function() {
    $('#box').addClass('soft');
    $('#box').css('left','400px');
  });
  $('#goLeftAndRight').on('click',function() {
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
     setTimeout(function() {
       $('#box').addClass('soft');
       $('#box').css('left','400px'); 
     }, 300);
       
  });
});
h2 {
  cursor:pointer;
}

#box {
  position: fixed;
  top:100px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

#box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.soft {
  transition: all 0.3s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <h2 id="goLeft">jump left</h2>
    <h2 id="goRight">slide right</h2>
    <h2 id="goLeftAndRight">jump left and slide right</h2>
    <div id="box"><p>use headers to move</div>
  </body>
</html>

Answer №2

No need for jQuery in this scenario.

Simply create a CSS class that includes the .jump-left transition:

.jump-left {
transform: translateX(-100px);
}

and another CSS class featuring the .slide-right animation:

.slide-right {
animation: slide-right-animation 1s ease-out;
}

@keyframes slide-right-animation {
  0% {transform: translateX(-100px);}
100% {transform: translateX(0);}
}

You can then utilize an onclick event listener to apply one class or the other, either separately or consecutively.

Example in Action:

var box = document.getElementsByClassName('box')[0];
var buttons = document.getElementsByTagName('button');

function buttonPress() {

    switch (true) {

        case (this.classList.contains('go-left')) :   
            box.setAttribute('class', 'box');
            box.classList.add('jump-left');
            break;
            
        case ((this.classList.contains('go-right')) && (box.classList.contains('jump-left'))) : 
            box.setAttribute('class', 'box');
            box.classList.add('slide-right');
            break;
        
        case (this.classList.contains('go-left-then-right')) :
            box.setAttribute('class', 'box');
            box.classList.add('jump-left');
            setTimeout(function(){
                box.classList.remove('jump-left');
                box.classList.add('slide-right');
            }, 300);
            break;
    }
}

for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', buttonPress, false);
}
button {
cursor:pointer;
}

.box {
  position: fixed;
  top:50px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

.box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.jump-left {
transform: translateX(-100px);
}

.slide-right {
animation: slide-right-animation 1s ease-out;
}

@keyframes slide-right-animation {
  0% {transform: translateX(-100px);}
100% {transform: translateX(0);}
}
<button type="button" class="go-left">jump left</button>
<button type="button" class="go-right">slide right</button>
<button type="button" class="go-left-then-right">jump left and slide right</button>

<div class="box"><p>Use buttons to move.</p></div>

Answer №3

Make sure to include the soft class by default and implement a timeout for the leftright function

$(document).ready(function() {
    $('#goLeft').on('click', function() {
        $('#box').css('left', '300px');
    });
    $('#goRight').on('click', function() {
        $('#box').css('left', '400px');
    });
    $('#goLeftAndRight').on('click', function() {
        //copy
        $('#box').css('left', '300px');
        setTimeout(function() {
            $('#box').css('left', '400px');
        }, 300);
        //Is timeout necessary?
        //copy
    });
});

h2 {
cursor:pointer;
}
#box {
position: fixed;
top:100px;
left:400px;
height:100px;
width:100px;
background-color:#358;
}
#box p {
padding:5px;
color:#fff;
text-align:center;
}
.soft {
transition: all 0.3s ease-out;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
   <body>
      <h2 id="goLeft">jump left</h2>
      <h2 id="goRight">slide right</h2>
      <h2 id="goLeftAndRight">jump left and slide right</h2>
      <div id="box" class="soft">
         <p>use headers to move
      </div>
   </body>
</html>

Check out this demo

Answer №4

To resolve the delay, a simple solution is to enclose the secondary portion of the jump left and slide right function within a setTimeout() function as shown below:

setTimeout(function(){
    $('#box').addClass('soft');
    $('#box').css('left','400px');
}, 100);

Here is a functioning snippet:

$(document).ready(function() {

  $('#goLeft').on('click',function() {
    $('#box').removeClass('soft').css('left','300px');
  });
  
  $('#goRight').on('click',function() {
    $('#box').addClass('soft').css('left','400px');
  });
  
  $('#goLeftAndRight').on('click',function() {
    $('#box').removeClass('soft').css('left','300px');
    
    //wait 100ms
    setTimeout(function(){
    $('#box').addClass('soft').css('left','400px');
    }, 100);
          
  });
});
h2 {
  cursor:pointer;
}

#box {
  position: fixed;
  top:100px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

#box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.soft {
  transition: all 0.3s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2 id="goLeft">jump left</h2>
    <h2 id="goRight">slide right</h2>
    <h2 id="goLeftAndRight">jump left and slide right</h2>
    <div id="box"><p>use headers to move</div>
  </body>

UPDATE:

Credit to Mohammad for suggesting an easier method to accomplish the jQuery functions. I have made adjustments in the snippet above to reflect that.

Answer №5

Implementing a timeout of 100 ms has proven to be effective.

Here is the code I utilized to replicate the scenario you described and test it:

<html>
<head>
<style>
h2 {
  cursor:pointer;
}

#box {
  position: fixed;
  top:100px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

#box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.soft {
  transition: all 0.3s ease-out;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $('#goLeft').on('click',function() {
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
  });
  $('#goRight').on('click',function() {
    $('#box').addClass('soft');
    $('#box').css('left','400px');
  });
  $('#goLeftAndRight').on('click',function() {
    //copy
    $('#box').removeClass('soft');
    $('#box').css('left','300px');
    //Need for timeout?
    //copy
    setTimeout(function(){
       $('#box').addClass('soft');
       $('#box').css('left','400px'); 
    }, 100);

  });
});
</script>
</head>
  <body>
    <h2 id="goLeft">jump left</h2>
    <h2 id="goRight">slide right</h2>
    <h2 id="goLeftAndRight">jump left and slide right</h2>
    <div id="box"><p>use headers to move</div>
  </body>
</html>

If this meets your requirements, please flag it as the accepted answer.

Answer №6

$('#goLeftAndRight').on('click',function() {
  //setting the initial position
  $('#box').removeClass('soft');
  $('#box').css('left','300px');

  // animation starts here
  setTimeout(function() {
    $('#box').addClass('soft');
    $('#box').css('left','400px'); 
  },0);
});

The setTimeout function waits for the next available time in the browser environment. Check out this link for more information: here

If you are interested in creating complex animations with different cue points, consider using a tool like GreenSock's Timelinelite

Answer №7

It's best to use the <code>addClass
function at the beginning of an animation.

$(document).ready(function() {
  $('#goLeft').on('click',function() {
    $('#box').removeClass('soft');
    $('#box').stop().animate({left:'300px'},{queue: false, duration:0});
  });
  $('#goRight').on('click',function() {
    $('#box').addClass('soft');
    $('#box').stop().animate({left:'400px'},{queue: false});
  });
  $('#goLeftAndRight').on('click',function() {
    //copy
    $('#box').removeClass('soft');
$('#box').stop().animate({left:'300px'}, { 
    queue: false, duration:0}).animate({left:'400px'},{ queue: false, start:
 function(){$('#box').addClass('soft'); } });


  });

});
h2 {
  cursor:pointer;
}

#box {
  position: fixed;
  top:100px;
  left:400px;
  height:100px;
  width:100px;
  background-color:#358;
}

#box p {
  padding:5px;
  color:#fff;
  text-align:center;
}

.soft {
  transition: all 0.3s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <h2 id="goLeft">jump left</h2>
    <h2 id="goRight">slide right</h2>
    <h2 id="goLeftAndRight">jump left and slide right</h2>
    <div id="box"><p>use headers to move</div>
  </body>
</html>
      

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

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

The web server retains the original file without replacing it

I am currently developing a website and attempting to upload a jQuery file using FileZilla: $(document).ready(function(){ function extractParameterValue(paramName) { var searchString = window.location.search.substring(1), i, val, params = sea ...

Utilizing Bootstrap Columns for Image Alignment: Struggling to Position an Image in the Center

For my latest project, I used Bootstrap to create a template that adapts well to different device breakpoints. Everything is working smoothly except for the positioning of the arrows on the sides of the image. I want them to be centered halfway down the ...

Looking for a way to limit the number of characters allowed per line in a textarea using jQuery

I have the following HTML textarea: <textarea name="splitRepComments" cols="20" rows="3" ></textarea> I have implemented a maxlength restriction using jQuery with the following function: var max = 100; $('#splitRepComments').bind(" ...

Exploring the world of HTML5 speed testing: getting started

Can anyone provide guidance on how to begin with an HTML5 bandwidth test? I am trying to replicate a flash-based version and any recommendations would be greatly appreciated. ...

Using jQuery to periodically update the content of a div with new HTML every few seconds

I have a simple snippet of HTML code: <div id="bio">Something...</div> Next, I need some jQuery code that is lightweight and efficient. It needs to run every 5 seconds without causing any browser issues. The problem I'm facing is decidi ...

JavaScript AJAX request not triggering properly

I'm encountering an issue with my code for retrieving data from MySQL. It seems that the ajax part is not working properly, as the 'ttt' alert is not being displayed. What could be causing this problem? function autoFill() { var claiman ...

Unable to set DIV width to 100% and show a scrollbar

I am facing an issue with the width of a DIV element on my webpage. Despite setting it to 100% width, it only takes up the visible window's width and not the full page width, especially when a horizontal scroll bar is displayed. Below is the HTML cod ...

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

Verify the presence of an image

I have a code snippet that I use to refresh an image in the browser. However, I want to enhance this code so that it first checks if the image exists before displaying it. If the image does not exist, I want to display the previous version of the picture i ...

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

Unusual Behavior of Codeigniter and Jquery .load() Function

Utilizing the .load() function to invoke a CI method and load some code into a div is pretty standard. However, I've encountered an issue where CI fails to load the correct content into the div if there is a trailing slash on the class name. Instead, ...

Remove each notification automatically in JavaScript after a specified period of time

I'm currently developing a basic notification system. Check out the jsfiddle I created here: https://jsfiddle.net/t9pvmzhh/3/ For some reason, jsfiddle is not showing all 4 notifications even though they display correctly on my end. I suspect there ...

What is the best way to implement CSS Background-size: cover; while also making room for a menu?

Recently, I came across the CSS property background-size: cover, but I encountered a problem. I want the area behind my navigation on the left to be black. However, when I leave black space in the image itself, it gets cropped off when the image resizes. ...

Arrange the divs vertically by utilizing flexbox styling

My goal is to use flexbox to vertically align three div blocks. Even though I can successfully align them horizontally, I am facing issues with vertical alignment. What could be the mistake in my approach? .banner { padding- ...

Encountering issues with Django when attempting to save JSON data in models

I have been attempting to use this code to store my JSON data in my Mvouchar model. However, I keep encountering an error. I am able to retrieve the data through cmd, but when I try to save it in my model, I encounter the error. I believe I may be making a ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Is there a way to get rid of this strange border surrounding my element?

Something strange is happening with the styling of my button. There seems to be an outline around it that I can't explain. Can anyone help me understand why this is happening? button { padding: 1em; background: transparent; border: none; } ...

Flashing bug in the outFunction of jquery hover()

My friends and I are working on a website for a class project, but we're running into a strange issue with the outFunction part of our hover function. Whenever the mouse hovers over an element, a grey square fades in using .fadeIn(), but then immediat ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...