Triggering transitionend event once with an added if condition

Currently, I have an application of an if statement that examines whether an element contains a style attribute. In the event that the style attribute is absent, it appends inline styling. Conversely, if the style attribute exists, it is removed. Furthermore, I am utilizing a transition in conjunction with the appended styling.

My objective is to execute //something following the conclusion of the transition utilizing transitionend. However, a persistent challenge I encounter is that each subsequent click on the element generates another transitionend event.

To better illustrate this issue, I have created a demonstration on JSFiddle.

I would greatly appreciate any assistance with this matter.

Answer №1

Remove event listener before initializing it

$('.box').unbind(transEnd);

This technique significantly reduces the number of alerts displayed

Previously: an increasing number were being displayed

Now: only 3-4 are shown each time

Answer №2

Each time a button is clicked, a new transitionEnd event handler is being added. It would be more efficient to have a single handler outside of the click function.

$('button').on('click', function () {

    var currentStyle = $('.box').attr('style')

    if (typeof currentStyle !== typeof undefined && currentStyle !== false) {
        $('.box').removeAttr("style");
    } else {
        $('.box').css('border-color', 'blue');
    }

});
var transEnd = 'transitionend webkitTransitionEnd oTransitionEnd'
$('.box').on(transEnd, function (e) {
    console.log(e.type, e.originalEvent.propertyName, e)
});

Another approach could be to utilize .one() to set up a handler that will fire only once like this:

$('button').on('click', function () {

    var currentStyle = $('.box').attr('style')
    var transEnd = 'transitionend webkitTransitionEnd oTransitionEnd'

    if (typeof currentStyle !== typeof undefined && currentStyle !== false) {
        $('.box').removeAttr("style");
    } else {
        $('.box').css('border-color', 'blue');
    }

    $('.box').one(transEnd, function (e) {
        alert('transition ended');
    });

});

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 is the best way to incorporate a percentage-based width scrollbar?

Help needed: I want to implement a scroll feature for the parent div but here's the catch - the width of the text inside the div needs to be in percentage. So, if there is a long name, it should scroll within the parent div. HTML: <div id="list"& ...

ReactJS: Alert for controlled form element

Utilizing inputs from Material-Ui, I am retrieving values from an API to populate these inputs. If the API does not return any values, the user must enter them manually. In my implementation, I am utilizing Hooks with the initial state defined as: const [ ...

Retrieve the id of an element from a JSON object

Dealing with quotes, single or double, can sometimes pose a challenge. I am working on a JavaScript function that sends data to a PHP file and receives a JSON response. Everything seems to be functioning correctly, except for the part where I need to out ...

Serialization in .NET and the weekcalendar: events that are not defined

I've been attempting to integrate the jQuery weekcalendar within a .net environment. The issue I'm encountering is that after making an ajax call to a custom webmethod that returns JSON, the weekcalendar plugin reports that events.events is undef ...

Exclude crypto-browserify from the NextJS build process

I have been dedicated to minimizing the build size of my app as much as possible, and I have observed that the crypto-browserify module is consuming a significant amount of space. While I understand that Next.js polyfills the node module if necessary, I wo ...

The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to wor ...

Difficulty in defining the impact of a function on a single menu

Q:: How can I restrict a jquery function to apply only on a specific set of list items in my website? $("li").mouseover(function(){ $(this).stop().animate({height:'230px'},{queue:false, duration:10, easing: 'easeOutBounce'}) ...

Do lengthy words sink while short words swim?

I need to display some text inside a box. To achieve this, I enclose my text within an <article> element. <article> <p>Here is the text that I want to display in a box.</p> </article> I then style it as a block with fix ...

What's the best way to organize Python objects for optimal JSON serialization?

Recently transitioning from JavaScript to Python, I am facing a challenge in understanding how to effectively communicate between client and server using JSON. Specifically, I am struggling to find the equivalent of an easily jsonifyable object attribute i ...

What is the best way to maintain the same height for a textarea and input fields?

What is the best way to align the message input field with the name and phone input fields? I need the height of the message input field to match the combined height of the three inputs on the left. It's crucial that the borders line up perfectly. I ...

What is causing my background image to move upward when I include this JavaScript code for FlashGallery?

There's an issue on my website where adding a flash gallery script is causing the background image to shift unexpectedly. You can view the affected page here: The culprit seems to be the "swfobject.js" script. I've identified this by toggling t ...

Encountered an issue while trying to reset the dropdown menu values on a Dash application when utilizing a clear button

I'm attempting to add a clear button for users to reset the values in a dropdown menu. However, when I run the application, I encounter the following error preventing me from selecting an option in the dropdown: Unable to access property 'leng ...

Creating responsive images in a navbar with HTML and CSS

I need help with this code snippet: <div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <div class="d-flex flex-row justify-content-center align-items-center"> <a cla ...

Transform the MUI Typescript Autocomplete component to output singular values of a specific property rather than a complete object

When utilizing MUI Autocomplete, the generic value specified in onChange / value is determined by the interface of the object set in the options property. For instance, consider an autocomplete with the following setup: <Autocomplete options={top ...

Issue with CSS background images

I'm having trouble trying to use this image as my background: . It just won't work... An error occurred while trying to set the background image. The declaration was dropped. Here is the HTML code: <div class="linkedin"></div> A ...

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 ...

Encountering a 403 error while attempting to retrieve an image

I'm currently facing difficulties in displaying firebase storage images on my Next.js application due to persistent 403 errors. When I add a document to Firestore, I upload an image to storage with a nested URL and use that URL to retrieve the image. ...

Change to the parent frame using webdriver

I am facing an issue while trying to switch to the parent frame or iFrame using webdriver.js. Although I have implemented a function that works, it only goes up to the second level of frames. When attempting to switch to the parent frame from a deeper fr ...

The wp email feature is malfunctioning under certain circumstances

I am facing an issue with my step form where I need to send an email when the next button is clicked. The problem is that the email is only being sent when I click the next button on the 2nd step. Below is the jQuery code I am using: let ajaxurl = 'a ...

The form submits immediately after jquery is activated

One challenge I'm facing involves multiple forms on a single page being submitted using jQuery. Currently, I have the following code snippet: $("form").submit(function (e) { // Submit form via Ajax }); The problem arises when the form is only s ...