What could be causing the malfunction of the .setAttribute() and .removeAttribute functions in my JavaScript program?

Below is a flashcard game I have developed:

Once a user enters the correct answer in the text box, "Correct!" is expected to be displayed in bold green font. The CSS attributes are then supposed to be removed shortly after. Here is the HTML code for the input area:

<div>
    <input type="text" id="answer" style="width: 80%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus><br>
</div>  

The accompanying JavaScript responsible for this functionality is as follows:

function checkAnswer(input, event){
    if(event.keyCode == 13){
        var answer = document.getElementById("answer").value.toLowerCase();
        var answer_style = document.getElementById("answer");
        for(var i = 0; i<qs.length; i++){
            if(answer == qs[cardIndex]["a"].toLowerCase()){
                **input.setAttribute("style", "color:green; font-weight:bold;");**
                input.value = "Correct!";
                setTimeout(function(){input.value="";},1000);
                **input.removeAttribute("style");**
            }else{
                input.value = "Incorrect!";
                setTimeout(function(){input.value="";},1000)
            }
        }
        if(input.value == "Correct!"){
            nextCard();
        }
    }
}

All functionalities within the checkAnswer function work except for the setAttribute and removeAttribute methods, which have been highlighted in the code snippet. I have attempted to place the removeAttribute method after the for loop without success. If the removeAttribute method is omitted, the setAttribute works, however, I do not want the text to remain green.

I would greatly appreciate any assistance with this matter!

Feel free to ask if further information is required to understand the issue!

Thank you!

Answer №1

After adding the style attribute, you are immediately removing it. Instead, schedule the removal for later by placing it inside the function passed to setTimeout, just like how input.value=""; works.

if(answer == qs[cardIndex]["a"].toLowerCase()){
    input.setAttribute("style", "color:green; font-weight:bold;");**
    input.value = "Correct!";
} else{
    input.value = "Incorrect!";
}
setTimeout(function(){
    input.value = "";
    input.removeAttribute("style");
}, 1000);

Answer №2

Setting and removing the attribute simultaneously can cause confusion. To achieve a delay before removal, consider using this approach:

setTimeout(function(){
    input.value="";
    input.removeAttribute("style");
},1000);

Answer №3

Make sure to place the input.removeAttribute function inside the setTimeout method like this:

            setTimeout(function(){input.value="";input.removeAttribute("style");},1000);

After 1 second, the style will be removed from the element.

Answer №4

It seems like utilizing input.removeAttribute("style"); is completely wiping out the original style. A simpler alternative would be to assign a CSS class and then define the style attributes within that class. While using setAttribute and removeAttribute methods may not prove beneficial in this context, they still offer similar functionalities.

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

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

The FuelUx scheduler forgets which day we've chosen when selecting weekly recurrence

When using the fuelUX scheduler, I noticed that after calling the method $('#myscheduler').scheduler("value","JSON VALUE") and selecting a weekly recurrence pattern, the information of the day gets lost. For example, if my input for the recurrenc ...

Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting element ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

What is the best way to link a file to index.html using feathers.js?

I am currently learning feathers and encountering a problem. I am attempting to include files similar to PHP's switch function. For instance: /src/middleware/index.js 'use strict'; const handler = require('feathers-errors/handler&ap ...

Exploring WordPress's Query Page with Posts

My current code successfully pulls posts from a specified category, but I am struggling to also include pages in the output. I have tried various methods, but haven't been able to pull in both posts and pages at the same time. HTML/PHP <?php quer ...

What is the best way to determine the operational schedule of online stores that have varying business days?

Struggling to automatically calculate the working days for various online stores that operate on different schedules. The challenge lies in some of these stores being open on weekends. It's important to note that JavaScript starts counting days of the ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

Having difficulties with the edit function in JavaScript To Do Application

After creating an edit button to modify a task, it functions properly for the initial task I create. However, when attempting to edit subsequent tasks, the edit function defaults back to modifying the input of the first task instead. With each new ta ...

Issue with displaying Bootstrap Tooltip

Recently, I launched a fresh website (currently residing on a sub-domain). However, I am facing an issue with the tooltip not showing up when hovering over the text Get the FinEco Bookmarklet. <span class="bookmarklet"><span class="fa fa-bookmark ...

Using JQUERY to create a smooth sliding transition as images change

Currently, I have set up three images (1.jpg, 2.jpg, 3.jpg) along with an image using the code: <img id="add" src="1.jpg"></img>. The width, height, and position of this additional image are adjusted as needed and are functioning correctly. Fur ...

modify a column in a database table when a different field is chosen

I am working on a basic table with 4 columns, two of which are dropdown menus with the classes "ddm1" and "ddm2". Here is what I am trying to achieve: Users should not be able to select from "ddm2" until they have selected an option from "ddm1". When ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...

What is the best way to display a success notification when a transaction is successfully executed in web SQL

var brand = "Glare"; var price = "3000$"; var color = "blue"; var success = tx.executeSql("INSERT INTO truck (brand, price, color) VALUES ('"+brand+"','"+price+"','"+color+"' ")"); if(success) { alert("successfully insert ...

Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first ti ...

Creating multiple rectangles and filling them with a color chosen by the user in Angular can be achieved by following these steps

Looking for advice on angular coding. I'm working on a project that requires creating multiple rectangles and filling them based on selected values. Can anyone suggest a module that would offer this functionality? ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

Leveraging AngularJS for parent-child communication through bindings in a unique and effective manner

I've come across the following code snippet: <div class="parent"> <div class="child"> and I have two directives, one for parent and one for child. When an event (such as a click) occurs on parent, I want something to happen on child ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...