Transition event listener fails to trigger

I am currently experimenting with transitions using JavaScript. My goal is to hide an element when the transition ends. I have set up an event listener using addEventListener, but the function does not seem to be executing.

var fun;

var transitions = {
    'transition':'transitionend',
    'OTransition': 'oTransitionEnd',
    'MozTransition': 'transitionend',
    'WebkitTransition': 'webkitTransitionEnd'
};

(function() {


    var i=0,
        containterget = document.querySelector('.container');
        elementGet = document.querySelector('.Number');


    fun = function(){
        i++;
        elementGet.innerHTML = i;
        elementGet.style.transform = 'translateX('+(containterget.offsetWidth - 40 -35)+'px)';
        elementGet.addEventListener(transitions,function(event){

            console.log("Transition End Execute");
            elementGet.style.display='none';
        });
    };
})();
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}
.container{
    border:1px solid green;
    max-width:85%;
    margin: 2em auto 0;
}

button{
    background-color: transparent;
    padding: 15px;
    margin: 0;
    color: #000;
    border: 2px solid #F44336;
    text-align: center;
    outline: 0;
    transition: opacity 0.3s;
}

button:hover{
    background-color: #F44336;
    color: white;
    opacity: .75;
}

button:hover{
    cursor: pointer;
    transition: opacity .4s;
}

span{
    display: inline-block;
    transition: transform 1.5s ease;
}

.Number{
    font-size: 4em;
    border: 1px solid black;
    /*transform: translateX(0);*/
}

.EndBoundry{
    float: right;
    font-size: 4em;
    border: 1px solid black;
}

.contain:after{
    content: "";
    display: table;
    clear: both;
}

.btn{
    text-align: center;
    margin: 2em 0;
}
<div class="container contain">
    <span class="Number">1</span>
    <span class="EndBoundary">E</span>
</div>
<div class="btn">
<button onclick="fun()">Number Transition Click</button>
</div>

Answer №1

Here is an example demonstrating the transitionend event. All explanations are provided within the code snippet.

CODE SNIPPET

// Get references to section#area and input#gone
var area = document.getElementById('area');
var chx = document.getElementById('gone');

// Add click event listener on #area calling offON()
area.addEventListener('click', offON, false);


function offON(e) {
  // Check which button was clicked 
  if (e.target !== e.currentTarget) {
    var tgt = e.target;

    // Toggle classes .on and .off of the clicked button
    tgt.classList.toggle('on');
    tgt.classList.toggle('off');
  }

  // Call transEND() function if checkbox is checked
  if (chx.checked) {
    transEND()
  }
}


function transEND() {
  // Add transitionend event listener on #area
  area.addEventListener("transitionend", function(e) {

    // Identify the clicked button
    if (e.target !== e.currentTarget) {
      var tgt = e.target;

      // Make clicked button disappear after transition
      tgt.style.display = 'none';
    }
  }, false);
}
/* All buttons have the same
|| transition effect. This transition depends on
|| another animatable style.
*/


/* The transition properties state:
|| ALL animatable styles will take
|| 3 seconds to animate,
|| with a timing function: ease,
|| and a delay of 300 milliseconds
*/

button {
  width: 120px;
  height: 40px;
  transition: all 3s ease .3s
}


/* Classes .on and .off represent
|| different states for each #id
*/

#fade.off {
  opacity: 1;
}

#fade.on {
  opacity: 0;
}

#move.off {
  transform: translateY(0);
}

#move.on {
  transform: translateY(200px);
}

#shrink.off {
  transform: scale(1);
}

#shrink.on {
  transform: scale(.3);
}

#gone {
  width: 18px;
  height: 18px;
}

p {
  font-size: 12px;
}
<p>Click each button. Then click them again (the "FADER" is still there and clickable)</p>
<p>Now click the checkbox and press the buttons again. If you cannot return the buttons to their original state, then the transitionend event handler has worked.</p>

<label for='gone'>Enable "transitionEND" </label>
<input id='gone' type='checkbox'>

<section id='area'>

  <button id='fade' class='off'>FADER</button>

  <button id='move' class='off'>MOVER</button>

  <button id='shrink' class='off'>SHRINKER</button>

</section>

Answer №2

Implement the "transitionend" event without any prefixes

elementGrab.addEventListener("transitionend", function(){});

Answer №3

To detect the end of a transition, you can listen for the 'transitionend' event on browsers that support it.

I made some adjustments to your code and included an id attribute to your button element.

Check out the code snippet below:


var fun;
var i = 0,
  containerGet = document.querySelector('.container');
elementGet = document.querySelector('.Number');
console.log(elementGet)

function execute(event) {

  console.log("Transition End Execute");
  alert("Transition End Execute");
  elementGet.style.display = 'none';
}
fun = function() {
  i++;
  elementGet.innerHTML = i;
  elementGet.style.transform = 'translateX(' + (containerGet.offsetWidth - 40 - 35) + 'px)';
  elementGet.addEventListener('transitionend', execute);
  elementGet.addEventListener('webkitTransitionEnd', execute);
  elementGet.addEventListener('mozTransitionEnd', execute);
  elementGet.addEventListener('oTransitionEnd', execute);

};

document.getElementById("target").addEventListener("click", fun)
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  border: 1px solid green;
  max-width: 85%;
  margin: 2em auto 0;
}

button {
  background-color: transparent;
  padding: 15px;
  margin: 0;
  color: #000;
  border: 2px solid #F44336;
  text-align: center;
  outline: 0;
  transition: opacity 0.3s;
}
// CSS code continues...

<div class="container contain">
  <span class="Number">1</span>
  <span class="EndBoundry">E</span>
</div>
<div class="btn">
  <script></script>
  <button id="target">Number Transition Click</button>
</div>

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

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

A step-by-step guide on recursively removing all empty array children [] from a nested JSON structure

When I receive a JSON response, I utilize nested JSON data from my GeoRegionCountries APIController and a custom class TreeView to structure the data for a plugin. The specific plugin I am using is a combo multi-select Treeview, accessible through this lin ...

Animated smooth updates in d3 line graphs are the key to creating dynamic and

I'm attempting to modify an example of Animated Line Graphs from: http://bl.ocks.org/benjchristensen/1148374 <div id="graph1" class="aGraph" style="width:600px; height:60px;"></div> <script> function draw(id, width, height, upd ...

Webdriverio: exploring the window object

I am experimenting with Webdriverio Testrunner using Selenium Standalone. I have encountered an issue while trying to check a global variable (window.myVar) in one of my tests. When attempting to return the window object, I am getting unexpected results i ...

How to retrieve the $0 element using Python Selenium

There is an unnamed element I can only access with a dollar sign: console.log($0); "100" In Python Selenium, how can I retrieve this element? I attempted the following: my_value=driver.find_element(By.NAME,"$0") However, it resulted i ...

My website built with the Celia template from Envato is loading slowly. It is taking longer than anticipated to load all the content

After purchasing the Celia template from Envato Element, I made several edits to the code for my website. You can view my hosted website on Github at: https://github.com/rosyhnguyen/rosyhnguyen.github.io. Additionally, I used the domain from Namecheap: Ev ...

Issues encountered while converting scss to css with gulp

I've been attempting to convert SCSS to CSS, and here's the code I've been working with. const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function() { return gulp.src(&apos ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

Retrieve the chosen language while utilizing the $translate feature

I have successfully integrated the $translate project from this source into my AngularJS application. While I have configured the default language in my app.config() using $translateProvider, I am now wondering how to retrieve the selected language within ...

Square Power Box

I have been attempting to create two equal sections, one displaying an image and the other showing text, both maintaining a square shape with identical width and height. I am using the Avada theme on Wordpress along with Element Builder and custom CSS to a ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Tally Every Number Encountered Within the Blog Archive

I've been facing some challenges putting together this jquery functionality. My original idea was to create a toggle effect for the archive's years and months. For example, when I click on a YEAR, it should toggle down to display all MONTHS, and ...

The React.js Redux reducer fails to add the item to the state

I'm just starting to learn about React.js and Redux. Currently, I am working on creating a basic shopping cart application. https://i.stack.imgur.com/BfvMY.png My goal is to have an item (such as a banana) added to the cart when clicked. (This sho ...

"Utilizing a custom CSS style for a half heart rating system

I am currently working on implementing a rating system using the font-awesome fa-heart class. While I have successfully colored the full heart, I am facing difficulty in filling only the first half of the heart in red. Despite my research efforts, all solu ...

Is the ng bootstrap modal within Angular failing to show up on the screen

In the midst of working on my project, I encountered an issue with opening a modal using ng bootstrap. Although I found a similar thread discussing this problem, it did not include bootstrap css. I decided to reference this example in hopes of resolving t ...

Using React to retrieve information from an array stored in the state

Hello there, I'm currently learning React and I'm facing an issue with my code. Within my state, I have an array and a function called submitted. This function is used to push new data into the array. Everything seems to be working fine except f ...

Utilizing a try/catch block for validating a JSON file is ineffective

I'm attempting to verify if a received string is JSON and I experimented with the code below: try { JSON.parse(-10); // Also tried with "-10" }catch(e) { console.log('inside catch'); } Surprisingly, the code never enters the catch ...

Tips for fetching integer numbers in a string in JavaScript in sequential order starting from the left side

Within an input element, users are required to input the price of a product. <input size=10 type="text" id="prd_price" title="prd_price" name="prd_price"> Users have the ability to enter Currency Symbols along with other characters, and we cannot ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

What is the best way to assign a value to a JSTL variable using JavaScript?

What is the process to assign a value to a JSTL variable using JavaScript? <script> function function1() { var val1 = document.getElementById('userName').value; <c:set var="user" value=""/> // how can I set val1 here? ...