What is the best way to assign a class to certain columns within a table?

I'm working on a code that generates random numbers for 3 columns and checks if each generated number exceeds +5/-5 of its previous number. However, I've encountered an issue where the first two columns always have the "blink" CSS applied to them, even when the generated number falls within the specified range. You can view my code on JSFiddle here: https://jsfiddle.net/d5ykog23/

Here is the code snippet:

var x = document.getElementById("tableContainer");
var i;
var n = 0;
var m;

$("#genNum").click(function(){

    for(j = 0; j < x.rows[1].cells.length; j++){
        m = x.rows[1].cells[j].innerHTML;
        i = Math.random() * (20 - 1) + 1;
        x.rows[1].cells[j].innerHTML = Math.round(i);
        n = x.rows[1].cells[j].innerHTML

        if (!((+m - 5) < n && (+m + 5) > n)) {
            $("#tableContainer th:nth-child(" + j + "), #tableContainer td:nth-child(" + j + ")").addClass("blink");
        }
    }
});

In addition, I have a question about removing the "blink" class from the entire table. I attempted the following code without success:

$("#stopAlarm").click(function(){
    $("#tableContainer").removeClass("blink");
});

Answer №1

For quick access to the solution, visit the link below: https://jsfiddle.net/r98yrpo3/

$(document).ready(function(){
    // var x = document.getElementById("tableContainer").rows[1].cells;
    var x = document.getElementById("tableContainer");
    var i;
    var n = 0;
    var m;
    var alarm = document.createElement("AUDIO");
    alarm.setAttribute("src", "alarm.mp3");

    alarm.addEventListener('ended', function() {
        this.play();
    }, false);


    $("#genNum").click(function(){
$("#tableContainer td").removeClass("blink");       
        $("#tableContainer th").removeClass("blink");
        for(j = 0; j < x.rows[1].cells.length; j++){
        
            m = x.rows[1].cells[j].innerHTML;
            
            i = Math.random() * (20 - 1) + 1;
            x.rows[1].cells[j].innerHTML = Math.round(i);
            n = x.rows[1].cells[j].innerHTML

               


            if (m-n <= 5 && m-n >=-5) {
                // console.log("flag");
                $("#tableContainer th:nth-child(" + (j+1) + "), #tableContainer td:nth-child(" + (j+1) + ")").addClass("blink");
                // alarm.play();
            }
        }
    });


    $("#stopAlarm").click(function(){
        $("#tableContainer td").removeClass("blink");       
        $("#tableContainer th").removeClass("blink");

    });
});
/*table formatting*/
table, th, td {
    border: 1px solid black;
}

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

/*
tr:nth-child(even) {
    background-color: #dddddd;
}
*/

.blink {
    animation:blink 300ms infinite alternate;
}

@keyframes blink {
    from { background-color: white; }
    to { background-color: red; }
};
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="myModule.js"></script>
        
        <title>Test</title>

    <body>
        <h1 id="greeting">Test Greetings</h1>
        <table id="tableContainer">
            <tr>
                <th field="col1">-----</th>
                <th field="col2">-----</th>
                <th field="col3">-----</th>
            </tr>
            <tr>
                <td>0</td>
                <td>0</td>
                <td>0</td>
            </tr>
            <tr>
                <td>-----</td>
                <td>-----</td>
                <td>-----</td>
            </tr>
        </table>
        
        <button id="stopAlarm" type="button">Stop Alarm</button>
        <button id="genNum" type="button">Generate Number</button>
    </body>

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

Do hooks get executed during every render phase?

Currently, I am utilizing the context API and hooks in my project. I have a total of 20 state variables, and every time one of them changes (resulting in setting states), the function is called again or re-renders. This has raised some concerns for me in t ...

The JSON parsing failed due to an expected '}' character missing

I'm in the process of making an ajax request $.ajax({ url: 'url', data: {}, method: 'POST', enctype: 'multipart/form-data', dataType: 'json', success: function(data){ // handle success ...

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Is it possible to shift the "ul" block of the navigation bar to the right without compromising the responsiveness toggle button functionality?

I'm currently using bootstrap NavBar and encountering an issue where moving the ul block to the right is disabling the toggle button responsiveness. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" c ...

Is there a way to ensure that mongoose waits for document creation before disconnecting?

I'm struggling to figure out what I'm doing wrong here. My goal is to finish seeding my database before disconnecting, but I can't seem to find the right solution. database.js import mongoose from 'mongoose'; mongoose.connect(pro ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

How can you navigate to different pages in Chrome by selecting radio buttons that are designed as clickable

Currently, I am in the process of developing a website for my job and I have come across a dilemma with two radio button options. To make the text and radio buttons function as links that redirect users to specific pages within the website, I utilized < ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

Issue with passing JSON data to a PHP file using CURL

I am currently working on a project that involves sending exam data with the exam-name and the selected number of questions from a list. Here is the project architecture I am following: To send JSON via AJAX to my make_exam.php file The questions.php fil ...

Issue an alert and refresh the webpage when a file extension upload script is detected

Here is the JavaScript code I'm using to restrict the file type extension during uploads: function TestFileType( fileName, fileTypes ) { if (!fileName) return; dots = fileName.split(".") //get the part AFTER the LAST period. fileType = "." + dots[do ...

When trying to target the checkbox value, the error "Object Expected"

My script successfully changes the value of a checkbox to toggle whether or not the user is in a specific Skype response group: var ie = WSH.CreateObject('InternetExplorer.Application'); url = "https://lyncfeg.DOMAIN.COM/RgsClients/Tab.a ...

Incorporate the ajax response into the design of the Material Design

I am looking to create a website that dynamically updates content using AJAX requests. I have JSON data that needs to be displayed in MDL cards. You can learn more about MDL cards here. Here is my AJAX code: $(document).ready(function(){ displayRecor ...

My custom PHP page designed to insert new records into a MySQL database table appears to be ineffective as it is not updating the table as intended

Firstly, I have confirmed that the const.php file is located in the same directory as the page. I am in the process of developing a web page that enables administrators to add multiple entries to a MySQL table through the website. The functionality involv ...

Amazon Banner Integration for Angular Version 4

Having some trouble getting an Amazon banner to display inside an angular material 2 card. The div appears empty and the banner is not rendering. Any idea what could be causing this issue? Below is the code snippet showcasing my attempts: <md-card clas ...

Is it necessary to utilize container or container-fluid within the grid system layout?

While similar questions may already exist on Stackoverflow, I believe the exact answer has yet to be found. Many suggest: "You should nest .col within .row, and ensure that .row is inside of .container." However, this concept still eludes me. I underst ...

The Electron NPM program is unable to locate the file:///eel.js, yet Python has no trouble locating it

I am currently developing a desktop application utilizing Python, JavaScript, HTML, and CSS. To connect Python to my application, I am using eel. Interestingly, everything works perfectly when I launch the desktop application through the Python terminal. ...

Choosing between Ajax.ActionLink and combining Html.ActionLink with a Jquery.Ajax call

One way to call an asp.net mvc controller is through Ajax.ActionLink("Get customers","GetCustomers","Customer"); Another method involves using Html.ActionLink and a jQuery ajax call. What sets these two approaches apart? ...

Adjust the parent div's background color when a radio button is selected

Is it possible to dynamically change the background color of a div that contains a radio button when the button is checked? Here is an example of the HTML code: <div class="custom-container"> <input id=“example” type="radio" name="opt ...