Performance issues with jquery addClass and removeClass functions observed in Internet Explorer 11

I am currently working on an application that monitors nodes within a cluster, and I have created a visual state example to demonstrate this. Each small box in the grid represents a node, and when hovering over a node, the rest of the nodes in that particular rack fade out.

If you would like to view the visual state image, please follow this link to Photobucket: visual state

While the fading effect works smoothly in Chrome and Firefox, there is a noticeable lag in IE 11. I understand that IE's javascript engine is slower compared to other browsers, so I would appreciate any input from the SO community on how to optimize my code for better performance. As someone who may not be the best front-end programmer, your suggestions are highly valued. Below are snippets of the code I am using:

Snippet from the Django template (each node has id="matrix-box-<node #>"):


    <tr>
    <td id="visual-state"><b>visual state</b></td>
    <td id="matrix" colspan=5>
        {% for row in v.22 %}
            {% if v.23 == "ca" %}
                {% if forloop.counter0|divisibleby:4 %}
                    <div id="rack-{% widthratio forloop.counter0 4 1 %}-{{ k }}" title="rack-{% widthratio forloop.counter0 4 1 %}">
                {% endif %}
            {% elif v.23 ==  "cs" %}
                {% if forloop.counter0|divisibleby:8 %}
                    <div id="rack-{% widthratio forloop.counter0 8 1 %}-{{ k }}" title="rack-{% widthratio forloop.counter0 8 1 %}">
                {% endif %}
            {% endif %}
            <div class="row">
            {% for elem in row %}
                {% if elem.1 == "#49E20E" %}
                    <div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #00DC00;" title="{{ elem.0 }}"></div>
                ...continued

CSS code snippet:


    .node {
        width: 4px;
        height: 4px;
        float: left;
        border: 1px solid #B0B0B0;
        background: #cccccf;
        margin: 0 !important;
        cursor: pointer;
        filter: alpha(opacity=100);
        opacity: 1;
        }

    .faded .node-faded {
        width: 4px;
        height: 4px;
        filter: alpha(opacity=50);
        opacity: .5;
     }
...more CSS code

Snippet from the JavaScript code:


    var node = null;
    var node_id = null;
    var rack = null;
    var nodes = null;

    $(document).ready(function(){
        $('[id^=matrix-box]').on({
            mouseenter: function(){
                node = $(this);
                rack = node.parent().parent();
                rack.addClass('faded');
                node.removeClass('node-faded').addClass('active');
            },
            mouseleave: function(){
                node.removeClass('active').addClass('node-faded');
                rack.removeClass('faded');
            },
            click: function(e){
            ...continuation

I welcome any constructive criticism that can help improve my code quality. Thank you for your assistance!

Answer №1

Without the opportunity to test, it becomes a game of guesswork. The approach is as follows:

$('[id^=matrix-box]').on({ mouseenter: function(){});

This attaches a new event listener to each element with an id starting with matrix-box. While not the worst idea, it may be sluggish if there are many such items.

To confirm this, here's a demo: http://jsfiddle.net/k3mjmdzp/3/

To address performance concerns, employing a delegated event listener would be beneficial.

Consider rewriting your code like so:

$(function () {
    $('#matrix').on('mouseenter mouseleave click', '[id^=matrix-box]', function (event) {
        console.log(event);
    });
});

Here's the updated demo: http://jsfiddle.net/k3mjmdzp/2/

This modification ensures that your code only has event listeners on $('#matrix'), rather than on every child node. It also proves useful when adding new items via ajax in the future.

You can verify event listeners under the Event Listeners tab in Chrome Developer Tools.

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

Hidden text within a webpage that remains concealed until a specific link is activated

Just getting started with HTML and wanting to add animation to my project. I have a vision of an animation where clicking on an image will split open a half page of text and stuff. It should be similar to this example: ...

Attempting to align content in the middle of the page across all web browsers

I need assistance with centering all the content on my website across different screen sizes and browsers. Currently, everything appears off-center and aligned to the left on various screens I have tested. You can view the HTML and CSS code in this link. H ...

Exploring the Differences Between NPM Jquery on the Client Side and Server

I'm still getting the hang of node and npm, so this question is more theoretical in nature. Recently, I decided to incorporate jQuery into my website by running npm install jquery, which placed a node_modules directory in my webpage's root along ...

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area. I'm unable to override parent element properties like border or outline. I also can't use pse ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

When working with Vuejs, if you try to use "axios" in a .js file, you may encounter an error

I am currently working with VueJS and attempting to send a GET request to my API. I am using axios, but encountering an issue when trying to import it. If I use require for the import, I receive this error: Uncaught ReferenceError: require is not defined. ...

In some cases, the Ajax reading or fetching variable may have difficulty retrieving the precise variable when working with CodeIgn

I've encountered a puzzling issue with my ajax code, or perhaps it's related to ajax itself. My code retrieves a value from a label and combines it with fresh data from the database. Strangely enough, every time I refresh the page, the output var ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

What are some creative ways to customize and animate the cursor or caret within an input field?

Just to clarify, I am working with React and Material-UI. I have a task at hand where I need to modify the appearance of the caret within an input element by adding an animation to it. I have managed to change its color using caret-color and set a default ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...

What is the best method for navigating and passing data in dynamic routing with NEXT.JS?

In the process of developing my next.js ecommerce app, I am utilizing Firebase to fetch product data. My goal is to have users click on a product and be redirected to a new page displaying the details of that particular product. However, despite using the ...

Potential Bug Detected in Internet Explorer on Mouseenter Event

I'm facing a challenge with my HTML/CSS code. I have a carousel that includes two li elements positioned absolutely on each side for navigation but they are not displaying correctly in IE versions 7-9 - they appear behind the main element regardless o ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Vue.js and the hidden input value that remains unseen

I am currently developing a shopping list application using Vue.js and I was wondering if there is a conventional method to achieve my requirements. My app consists of a list of items with add and delete buttons: https://i.stack.imgur.com/yQfcz.png const ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Delete the span element if the password requirements are satisfied

I am implementing password rules using span elements. I aim to dynamically remove each span that displays a rule once the input conditions are met. Currently, I have succeeded in removing the span related to the minimum length requirement but I am unsure h ...