Is there a way to stop a jquery event before it begins and target a specific one instead?

I'm facing a challenge with the initial load of my webpage where the header appears in 3 parts slowly and dramatically. On top of that, I have tabs that trigger transitions between different content "pages." The issue arises when a tab is clicked before the initial header animation is completed, causing overlap and messy transitions. I've attempted to use stop() and finish() functions but I'm not entirely sure where they should be placed. My goal is to ensure that when a tab is clicked, the initial animation finishes instantly before triggering any other animations. However, identifying and targeting that specific animation has proven tricky.

Here's the code snippet for the initial header animation:

$.fn.topSlide1 = function() {
  setTimeout ( function()
              {
    $('.part1').delay(1000).animate({ opacity: '1'  }, 'slow');
    setTimeout (function() {
      $('.part2').delay(1000).animate({  opacity: '1'}, 'slow');
      setTimeout(function() {
        $('.part3').delay(1000).animate({  opacity: '1'  }, 'slow');
      }, 1100);
    }, 1100);

  }, 1100);


  return this;

}

And here's the code snippet for handling tab clicks if the initial page is still displayed:

if (current === '#mag1')

{
  /*Stop animation code here??*/

  /*Initiates fading away transition*/
  $('.part1').animate({ opacity:'0'}, 'slow');
  $('.part2').animate({ opacity:'0'}, 'slow');
  $('.part3').animate({ opacity:'0'}, 'slow');
  $('.bio').fadeDown();

  /*Slides up new page*/
  $(id).fadeUp();
  current = id;

}

Answer №1

To execute a function upon completion, simply include it at the end of your code:

$('.element').fadeOut('fast', function() {
    // Additional actions to take after the animation is complete
    console.log('Animation finished');
});

Answer №2

If you already have a click handler set up, it's advisable to use the .stop function before starting your next animation. The stop function allows you to specify whether to jump to the end of the animation. Here is an example of how you can incorporate this:

if (current == '#mag1')

{
  /*                           clearQueue, jumpToEnd*/
  $('.part1, .part2, .part3').stop(true, true);

  /*Starts the fading away transition*/
  $('.part1').animate({ opacity:'0'}, 'slow');
  $('.part2').animate({ opacity:'0'}, 'slow');
  $('.part3').animate({ opacity:'0'}, 'slow');
  $('.bio').fadeDown();

  /*Slides up new page*/
  $(id).fadeUp();
  current = id;

}

For more information on jQuery.stop, refer to: https://api.jquery.com/stop/

Check out this interactive JsFiddle Example: https://jsfiddle.net/rf1y60xz/1/

$(document).ready(function() {
// Fade in slowly
    $('.move').animate({opacity: 1}, 5000);
  $('button').on('click', function() {
      $('.move').stop(true, true);
    // Fade out and perform other actions
    $('.move').animate({opacity: 0});
  })
});

Here's a slightly more complex example that waits for the opacity animation to finish before moving another box:

View the example here: https://jsfiddle.net/rf1y60xz/2/

$(document).ready(function() {
// Fade in slowly
    $('.move').animate({opacity: 1}, 5000);
  $('button').on('click', function() {
      $('.move').stop(true, true);
    // Fade out and then proceed with other actions
    $('.move').animate({opacity: 0}, function () {
        $('.move2')
        .css('opacity', 1)
        .animate({left: 400});
    });
  })
});

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

Using JavaScript regular expressions with a forward slash included in the string

My node application is connected to mongodb using the native driver. Within my documents, there is a field called "parent" with values like "parent":"root/test/dir/". I am attempting to retrieve all documents where the "parent" field contains "root/test" ...

How can I choose multiple criteria by utilizing the indexOf('EXAMPLE.com') method? Is there a way to add additional examples for selection?

I'm currently working on extracting specific usernames from a training portal: Up to this point, I've come up with some code that's able to select all emails containing EXAMPLE.com (as shown below) Is there anyone who could modify this cod ...

The "settings" injection was not located. The Vue composition API is encountering problems with providing and injecting

I'm encountering an issue while attempting to pass a reactive object using Vue's provide and inject method. I keep receiving the warning message [Vue warn]: injection "settings" not found. and when I try to log out settings, it shows up as undefi ...

Tips for limiting the .click function to only the initial image in order to prevent loading all images within the container

I am facing a situation where multiple images are being returned into a specific div, which is working as intended. <div class="go" id="container"></div> Upon clicking on an image, it is loaded into a modal popup. However, instead of capturin ...

When trying to access request.json within Flask, an error is triggered

I'm currently using Flask 0.10.1 and have a Flask function with the following starting code: @app.route('/logs', methods=['POST']) def add_log(): db = get_db() print("\ninside /logs POST\n===================") ...

Problem arises with chai-http middleware when employing dynamic imports in chai 5.1.1 version

Currently, I am utilizing npm chai version 5.1.1 which has transitioned to supporting only imports and not requires. My use of dynamic imports has been successful so far. However, I have encountered an issue when incorporating the chai-http middleware with ...

Error: Cannot access the 'question' property of an undefined node

I am facing an issue with a command-line application that I am currently transitioning into a client/server application. Within the class I have written, there is a function responsible for randomly extracting questions. However, I have observed instances ...

Issue with min-height property in IE8 (and potentially other browser versions)

Trying to design a web page with 3 sections, each occupying 100% of the window height. Managed to make it work on Chrome, Firefox, and Safari, but facing compatibility issues with IE8 and possibly other versions. Test out the page here: Here's the H ...

Exploring the placement and animation of a Flexbox dropdown menu

I'm currently working on designing a header with three main elements: ---------- LOGO ---------- hidden navigation bar ---------- BUTTON ---------- This header layout is supposed to grow into the following structure: ---------- LOGO ------ ...

Setting a default blank value in Select2 multiple mode

I have a dynamic multiple choice input that utilizes the Select2 plugin. I want to include a "blank" option with an empty value and a title to give the appearance of nothing being selected, but indicate to the user that an option is indeed chosen as "All." ...

Creating a series of progress bars in Bootstrap that feature labels positioned to the left and moving towards the right

I am trying to create multiple progress bars using Bootstrap 4 with labels or text on the outer left side. Currently, the bars are appearing like an inverted stair when multiple bars are added. https://i.sstatic.net/zHhfX.png Here is the code I have so f ...

Enhance your Facebook sharing by including unique element IDs as hashes in PHP code

Over at this specific page, I have a collection of neatly presented mp3 files in stylish boxes. Each one of these boxes features a Facebook share button. I'm looking to incorporate the unique identifier for each box, such as (mp3jWrap_0, mp3jWrap_1, ...

Guide to incorporating a logo into a personalized WordPress theme

In the process of creating a WordPress theme from scratch, I've hit a roadblock while trying to incorporate a logo in the top left corner of the page where the title would normally be displayed. <h1> <a href="<?php echo home_url(); ?> ...

How come my website is loading a JavaScript file with outdated content?

After making edits to a JavaScript file that replaces specific HTML tags with new language translations, I noticed that the changes were not reflected correctly on the website. Even after clearing my history and cache, Firebug still showed the old content ...

How can I incorporate "Context" into route configuration?

I am facing an issue with adding the searchContext context in my App.js file to provide access to variables in my Navbar and Results components. Despite trying various approaches, I have been unsuccessful so far. Here is the code snippet: <Router> ...

How Bootstrap Navigation is negatively impacting the width of the website

I am experiencing a problem with site width changes in the navigation. I have checked margins and padding, but couldn't find a solution to fix the issue. It seems like the row element is causing the problem, but I'm not sure why. Please assist me ...

Get an item from within a collection of objects

I'm in the process of creating a board game, and I am looking to implement a feature where clicking on a specific location will turn it red. I have an array of divs, but I'm struggling to figure out how to target and change the color of a specifi ...

Tips for retrieving a collection of nodes using a specific CSS selector in jQuery

How can I select a set of nodes using a CSS selector in jQuery? In YUI, this is accomplished with YAHOO.util.Selector.query(abc, root), where abc represents the CSS. Can anyone help me convert this functionality to jQuery? ...

The sequence of loading styles is respected, yet Bootstrap continues to take precedence over the WordPress child

After putting together a WordPress child theme that correctly displays Bootstrap and child-styles.css in the source code, I encountered an issue: View Source Code Stylesheet Order Upon inspecting with Chrome, it's apparent that the color of my link ...

I am not pleased with the result produced by using a frameset in HTML

Is there a way to split a web page into 3 columns and 3 rows, but have all the content visible on one page? Can I show it across multiple pages where scrolling affects the top frameset's scrollbar and not the third row's scrollbar? This is the H ...