Exploring alternatives to setTimeOut() for precise timing of Javascript events, especially when incorporating third party events

Here is the HTML element stack that I am working with:

<div class="btn-group btnSortAssType" data-toggle="buttons">
    <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="m">Model
    </label>
    <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="n">Assignment
    </label>
    <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="p">Multi
    </label>
</div>

The buttons above are not mutually exclusive, so I am handling array operations and showing/hiding elements accordingly.

 $('.btnSortAssType').on('click', function (event) {
        let $allLables;
        var assTypeToShow = [];
        $(`.top-row`).hide();
        setTimeout(function () {
            $allLables = $('.btnSortAssType label.active');
            $allLables.each((index, label) =>{
                $(`.top-row[assignment_type="${$(label).find('input').val()}"]`).show();

            });
        })
    });

In the JavaScript code above, you may notice the use of setTimeout(). This is because without it, the last click might be missed. If 2 out of 3 elements are active and you click on the last inactive one, it will still show 2 active elements.

This issue seems to be related to event timing between my code and bootstrap.js. It appears that the method setting the element as active in Bootstrap somehow occurs after my code runs. By using setTimeout(), I ensure that my code waits for any previous events to finish before executing (essentially a null delay).

Although the implementation with setTimeout() works seamlessly, I believe there might be a better way to handle this situation without resorting to this "hack". I would appreciate any insights or suggestions on how to improve this. Thank you for your help!

Best regards, Bud

Answer №1

When dealing with the Bootstrap handler, it is linked to the document and functions in the bubbling phase. This means that event listeners attached to child elements of the document, which also operate in the bubbling phase, will be activated prior to the Bootstrap handlers:

$('.btnSortAssType').on('click', function(event) {
  console.log($('.active').length);
});
.active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.js"></script>
<div class="btn-group btnSortAssType" data-toggle="buttons">
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="m" checked>Model
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="n" checked>Assignment
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="p" checked>Multi
    </label>
</div></code></pre>
</div>
</div>
</p>

<p>To address this situation, you can attach your event handler to the document as well, <em>and</em> make sure your script executes after Bootstrap's (as listeners attached to the same element are triggered in the order they were attached):</p>

<p><div>
<div>
<pre class="lang-js"><code>$(document).on('click', '.btnSortAssType', function(event) {
  console.log($('.active').length);
});
.active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.js"></script>
<div class="btn-group btnSortAssType" data-toggle="buttons">
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="m" checked>Model
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="n" checked>Assignment
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="p" checked>Multi
    </label>
</div></code></pre>
</div>
</div>
</p>
</div></answer1>
<exanswer1><div class="answer" i="59371244" l="4.0" c="1576564367" m="1576576117" a="Q2VydGFpblBlcmZvcm1hbmNl" ai="9515207">
<p>The Bootstrap handler is connected to the document and executes during the bubbling phase. Therefore, event listeners attached to descendants of the document that also execute in the bubbling phase will fire <em>before</em> the Bootstrap handlers:</p>

<p><div>
<div>
<pre class="lang-js"><code>$('.btnSortAssType').on('click', function(event) {
  console.log($('.active').length);
});
.active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.js"></script>
<div class="btn-group btnSortAssType" data-toggle="buttons">
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="m" checked>Model
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="n" checked>Assignment
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="p" checked>Multi
    </label>
</div>

You can correct this by attaching your event handler to the document as well, and running your script after Bootstrap's (since listeners attached to the same element will run in the order in which they're attached):

$(document).on('click', '.btnSortAssType', function(event) {
  console.log($('.active').length);
});
.active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.js"></script>
<div class="btn-group btnSortAssType" data-toggle="buttons">
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="m" checked>Model
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="n" checked>Assignment
    </label>
  <label class="btn ink-reaction btn-primary active">
        <input type="checkbox" value="p" checked>Multi
    </label>
</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

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML an ...

The Nuxt auth module fails to update the user's loggedin status within the store state

Currently, I am implementing Authentication functionality using the Nuxt Auth Module. My frontend is built on Nuxt Js, while my backend is running Laravel 5.7 In nuxt.config.js, I have configured the auth settings as follows: auth: { strategies: { ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...

Removing unnecessary keys from intricate JSON data (with the use of pure JavaScript)

I've experimented with various methods to dynamically parse and remove keys with empty values from a JSON file using JavaScript. Currently, I can successfully delete non-nested keys, except for empty strings that have a length greater than 0. My mai ...

Why is it that one of my useQuery hooks is returning a value while the other one is returning undefined?

I'm currently facing an issue with React Query where one of my useQuery hooks is logging undefined while the other one is displaying the correct data. Both functions are async and perform similar tasks. I've been troubleshooting this problem for ...

Search for spaces and brackets in a file name, excluding the file extension using Regular Expressions

Currently utilizing javascript and I have a specific string let filename1 = "excluder version(1).pdf" Keep in mind that the extension may vary, like jpg or png I am looking to replace the original string with the desired outcome is it possible ...

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

What is the best way to modify the height of a div before fetching an image using Ajax, and then revert it back to its original height once the image has been

Using a form and Ajax, I'm dynamically pulling an image to replace another image in the .results div. Initially, when the image was removed and loaded, the page jumped up and down, so I tried adding a style attribute to set the div height and then rem ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Encountering issues when using react-leaflet in a React project with webpack integration

I've been attempting to import react-leaflet into my project without actually rendering any maps, but I keep getting this error message. TypeError: Object(...) is not a function I am certain that the issue stems from the import statement, as indica ...

CSS code for vertical navigation arrows to remain on both the left and right sides of the webpage

I'm struggling a bit with the CSS. I want to recreate the same effect as seen on . The left and right navigation arrows stay fixed vertically even when scrolling up or down the page. Does anyone have any code examples for that? ...

Using require to access an Immediately Invoked Function Expression variable from another file in Node.js

File 1 - Monitor.js var MONITOR = (function () { // Code for Monitoring return { doThing: function() { doThing(); } }; })(); File 2 - Test.js var monitor = require('../public/js/monitor.js'); I am trying to access the doThing() funct ...

How do I send a 404 error in Node JS Express when a third party API receives a bad request?

I've set up a Node JS server with a route handler that sends a request to a third-party API to retrieve a username: app.get('/players/:player', apiLimiter, function(request, response) { const player = request.params.player; const api_url = ...

I am facing an issue with the Ionic Framework where the Javascript function for JWPlayer only works after the page is reloaded. Can anyone help

I'm currently troubleshooting the use of JWPlayer for streaming videos in an Ionic app. However, I've encountered a problem. The player only seems to load when I refresh the page, rather than when I navigate through the list of videos. Here is ...

Exploring jQuery.each: A guide to navigating JSON objects

As a beginner in working with JSON, I am struggling to iterate over a JSON response received via AJAX. My objective is to extract and loop through checkbox values retrieved from a database table such as 2,3,7,9,3. However, I am currently facing difficultie ...

Encountered a Node.js build error related to a Java module

Encountering issues while attempting to integrate the JAVA module into my NodeJS application on Ubuntu: NodeJS: v6.2.0 NPM: 3.8.9 Node-gyp: v3.3.1 Python: 2.7.12 GCC: 5.4.0 Despite having all the required dependencies, I consistently face errors when ...

Exploring the versatility of HTTP actions in Express: Using GET and

Currently, I am setting up a server through express. While everything is running smoothly with my project, I have a small query that is not related to the project itself. My confusion lies in the requirement to use the GET method when, in my opinion, usi ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...