How to retrieve an element by its class using JavaScript and Jquery while implementing a

I am working on creating a quiz example using Jquery, but I am facing some challenges when trying to manipulate CSS classes with hover in Jquery.

.right{
  background-color: white;
}
.wrong {
  background-color: white;
}
.right:hover {
   background-color: yellow;
}.wrong:hover {
   background-color: yellow;
}

In my CSS, I have defined the initial background colors for classes right and wrong. Using Jquery, my goal is to change these colors to green and red respectively, and then return them back to normal after 1.5 seconds as shown below:

//change colors
$('.right').click( function() {
    var $el = $(".wrong"),
    originalColor = $el.css("background-color");
    $('.wrong').css("background-color" , "red");
    $('.right').css("background-color" , "green");
    test(originalColor);
})

async function test(originalColor){
    await sleep(1500);
    $('.wrong').css("background-color" , originalColor);
    $('.right').css("background-color" , originalColor);
}

function sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
//change colors

Everything seems to be working fine, except for the hover effect. After the first Jquery click event, the hover color is lost. It appears that the line $el2 = $(".wrong:hover") may be causing this issue. Can someone help me modify the code so that the background-color: yellow; on hover is retained even after the first Jquery function?

Fiddle example: Fiddle example

Answer №1

Implementing class changes instead of CSS styling

 $('.success,.failure').click( function() {
        var $element = $(".failure"),
        originalColor = $element.css("background-color");
        var $element2 = $(".failure:hover"),
        hoverColor = $element2.css("background-color:hover");
        $('.failure').addClass("highlight-red");
        $('.success').addClass("highlight-green");
        checkResults(originalColor,hoverColor);
        })


     async function checkResults(originalColor,hoverColor){
       await sleep(1500);
        $('.failure').removeClass("highlight-red");
        $('.success').removeClass("highlight-green");
     }
    function sleep(ms){
      return new Promise(resolve => setTimeout(resolve, ms));
    }
div{
  width:50%;
  height:40px;
  float:left;
}
.success{
  background-color: white;
}
.failure {
  background-color: white;
}
.success:hover {
   background-color: yellow;
}.failure:hover {
   background-color: yellow;
}
.highlight-red,.highlight-red:hover{
  background-color: red;
}
.highlight-green,.highlight-green:hover{
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="success">Correct</div>
<div class="failure">Incorrect</div>

Answer №2

From my knowledge and personal experience (experience being the greatest teacher), :pseudo elements do not exist within the DOM. Therefore, Javascript selectors are unable to target or modify them.

An alternative approach would be to assign classes for hover effects, enabling you to manipulate or observe attributes of that specific class; such as ".hover"

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

It seems that in Laravel 5.3, it's challenging to add a script to a view for an autocomplete

Currently, I am working with Laravel 5.3 for my internship. However, I have encountered a frustrating issue that I need help with: I am trying to implement an "autocomplete" field on a page, but it doesn't seem to be functioning correctly. The error ...

Submission successful, unfortunately unable to upload files in the combined form

When attempting to combine submit and upload in one form, I encountered an issue with the upload process, but submitting the form is working fine. Using JQuery and Ajax : $("#oqcsubmit").click(function() { if($("#oqc").valid()) { var para ...

Transfer all HTML variables using AJAX with jQuery

Is it possible to pass all HTML tag values to another file using AJAX? $.ajax({ url:"myp.php", type:'POST', data: //here I want to include all possible element values in the current HTML document }); Any suggestions or ideas on how to ...

Working with JSON data in PHP and JavaScript

I'm attempting to send a JavaScript object to a PHP script using jquery.ajax(), like so: var bigArray = new Object(); //Code //Start loop bigArray[x] = {name: exname, id: exID, order:e, set: setBox, inc: incBox, example: exampleBox, day: i}; It&apos ...

The error "Property 'user' does not exist on type 'Session'." occurred while attempting to pass session data using express-session and accessing req.session.user

I'm currently working on creating a basic login form for users to access a website, where I plan to store their session data in a session cookie. The express-session documentation provides the following example for setting it up: app.post('/login ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Can multiple print buttons in different modals be connected to individual divs within their respective modals?

I am currently developing a webpage using the Foundation 5 framework that features a table of information. Each row in the table contains a link that, when clicked, opens a specific modal displaying detailed information related to that row. I want to add a ...

Conceal table rows with JQuery in html

I need assistance in hiding a row in an HTML Table that contains a value of 0.00 in the third column. I've attempted using JQuery and CSS, but so far no success. Below is the code snippet: <%@ page language="java" contentType="text/html; charset= ...

Conceal list item using Jquery on the beginning of a new month

As someone with experience in CSS rather than programming, I find jQuery a bit challenging. However, I am trying to achieve a specific task and could use some help. I have an unordered list (UL) with one list item (li) representing each month. My goal is t ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

Retrieving information from embedded JavaScript code

The web page I am scraping contains inline JavaScript that dynamically generates telephone numbers inside a script tag. These numbers are not visible in the page source, making it challenging to scrape using common methods like x-path and beautiful soup. U ...

Development of "individual profiles"

This is my first time venturing into web app development and everything is quite unfamiliar to me. I have successfully set up a couple of PHP scripts to interact with an SQL database for user login and registration purposes. However, I now wish to implem ...

Issue encountered while generating a dynamic listing using Angular

My goal is to generate a dynamic table using Angular. The idea is to create a function where the user inputs the number of rows and columns, and based on those values, a table will be created with the specified rows and columns. However, I am facing an iss ...

I am receiving the same URL for multiple files stored on Firebase Storage

After attempting to upload multiple files to Firebase Storage and retrieve the download URL for each one, I encountered an issue where all files were successfully uploaded but only the URL for the last file was retrieved. The following code snippet shows ...

Preserve scripts when loading content into a pjax container

I am currently working on my WordPress site and incorporating pjax for the first time. My goal is to update both the #main container and a separate div that houses a stretched background slider. The challenge I encountered was with the script tag associate ...

A fixed header for tables that shifts along with horizontal scrolling

Seeking assistance with a persistent issue - I have a table with a fixed header on vertical scroll (see CSS and Javascript below), but the header fails to move horizontally when I scroll. window.onscroll = functi ...

Accessing the path to an imported file in Node.js

Currently, I am working on a parser and encountering imports such as ../modules/greeting.js. Additionally, I have an absolute path to the file from where I performed the import: C:\Desktop\Folder\src\scripts\main.js. I am seeking ...

Invoking a PHP function file through Ajax

Currently, I am utilizing Ajax with Bootstrap Modal to retrieve content from a Database. One of the functions in my functions file is responsible for verifying the existence of a remote file: function checkRemoteFile($url) { $ch = curl_init(); cur ...

Sizing Bootstrap Carousel Controls

Is there a way to adjust the size of controls in the bootstrap carousel using CSS? I'm working with Bootstrap 4 and have attempted the following, but it only seems to reposition them. .carousel-contol-prev { height: 26%; top: 33%; wid ...

What is the reason for the initial display of an empty option when using AngularJS to select an

Every time I refresh the page, the initial option is blank. How can I set Any Make as the default selection? Below is the code snippet from my view: <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-chan ...