Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this:

HTML:

<div class="container" id="cont">
  <div class="box show"></div>
</div>


CSS:

.container {
  width: 100vw;
  height: 100vh;
}

.box {
  position: absolute;
  right: 0px;
  width: 0px;
  height: 100px;
  transition-duration: 1500ms;
  transition-property: width;
  transition-delay: 1s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container:hover .box {
  width: 500px;
}

.show {
  background: #9CEAEF;
  transition-timing-function: ease-out;
}

I am trying to integrate a JavaScript countdown, where when it reaches 10, I want to display the CSS animation with some text and have it stay for 8 seconds before reverting back. I have been struggling to find a solution for over an hour.

function updateCountdown() {
    var timeLeft = Math.round(vid.duration) - Math.round(vid.currentTime);
    if (timeLeft == 10 && shown == false) {
        console.log(timeLeft)
        // here i want to trigger the css 
        shown = true
    }else if (timeLeft < 2) {
        vid.removeEventListener('timeupdate', updateCountdown);
        // here i want to relase the css back
    }
}

Check out the codepen link for more details: https://codepen.io/burlacu-daniel-robert/pen/bGEyYzN

Answer №1

Modifying the :hover selector directly with Javascript is not possible. Instead, you can utilize the mouseenter event to adjust the style and then return it to its original state when the mouseleave event occurs.

Answer №2

The use of pseudo classes such as :hover does not target a specific element, but rather any element that meets the criteria set forth in the stylesheet rule. To implement the desired styling changes, you can modify the existing stylesheet rule, add a new rule, or create a new stylesheet to accommodate the :hover functionality.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

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

What is the reason Angular is unable to locate a controller for a directive in an external file?

As a newcomer to Angular, I'm struggling to comprehend John Papa's recommendations. His guidelines suggest placing controller logic inside directives, but this approach doesn't seem intuitive to me. Despite my efforts to implement it myself, ...

Encountered an unhandled rejection error: TypeError: Unable to destructure the property 'protocol' of 'window.location' because it is undefined

I integrated the react-tradingview-widget into my nextjs project and it was working perfectly on version 10.2.3. However, after upgrading to version 12.1.4, I encountered an error when trying to reload the tradingview component. The error message was: unh ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

How to correct header alignment in HTML for Google Table

Utilizing the google visualization table to generate a html table, I have successfully fixed the top section of the html using the stuckpart div. This ensures that regardless of how I scroll, the button remains in place. However, I now aim to fix the table ...

Generating forms dynamically with Vuetify

When working with HTML code, the structure looks like this: <v-col cols="12" md="4" v-for="(leadObj, i) in lead.data" :key="i" > <v-col v-if="leadObj.inputType !=='select'"> ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

Leveraging the power of Ajax and Javascript to handle and process conditional if/else statements

Hey there, I'm new around here so I hope I got this right. Currently, I'm diving into the Ajax for Dummies book after enjoying the PHP one years ago. However, I've hit a roadblock with my first real Ajax program. It took me ages to locate th ...

Seamless side-to-side navigation

Currently, I am working on a website that has horizontal overflow instead of the common vertical scroll. While everything seems to be functioning properly, I need to enhance the user experience by adjusting the amount scrolled to move larger sections of th ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math pro ...

Grid system not being followed by table in Bootstrap layout

I'm struggling to figure out why the table I have doesn't follow Bootstrap's grid system. It took me a good 2 hours to pinpoint and fix the issue. Any help would be greatly appreciated. I could share the code, but it might be easier for you ...

The Google Maps App fails to launch now

Recently, my map started experiencing issues. The problem seems to be related to the HTML using a javascript and css file that is loaded from Google Drive for display. However, when I directly load these files from my computer, it works perfectly fine. Bel ...

How to showcase information stored in Firebase Realtime Database within an Ionic application

Looking to list all children of "Requests" from my firebase realtime database in a structured format. Here's a snapshot of how the database is organized: https://i.stack.imgur.com/5fKQP.png I have successfully fetched the data from Firebase as JSON: ...

Having trouble understanding the odd behavior in IE7. Suddenly seeing a scrollbar appear when hovering

The webpage layout I am currently experiencing issues with can be found at the following link: When viewing this page in ie7 or ie8 Compatibility View mode, a strange horizontal scrollbar appears whenever I hover over one of the menu items. It seems that ...

The issue of conflicting checkboxes and types plugins in jstree

Working on constructing a tree with the jstree JavaScript library and incorporating two jstree plugins: checkbox plugin types plugin Below is a snippet of code for reference: var mydata=[ id: "1", parent: "#", text: "node1", }, { id: "2", parent: " ...

Is there a method to implement a pop-in animated contact form without the use of Javascript or query selectors?

Although I was successful in creating a contact form with this functionality using Javascript, I encountered some difficulties when attempting to achieve the same result without it. My goal is for the form to slide in from the right when the "open" icon is ...

Having trouble with an onClick function not working on a .php webpage?

I recently developed a simple JavaScript script that dynamically loads an image based on user input in a text field (e.g., entering 'brick1' loads brick1.jpg). Although this works fine on a regular HTML page, I faced issues triggering the onClick ...

Nuxt - Dynamically manage routes while utilizing server-side rendering functionality

Hello! I have a question for you: I have: a Nuxt app set up with target: 'server' in the nuxt.config.js an API that provides me with a template associated with a given path (for example, /person/maxime will return template: PersonsSingle) a vue ...

What is the best way to modify the selection text background with CSS?

Does anyone know the method for modifying the selection text background in CSS? Many modern websites opt for a personalized background color instead of the traditional blue? ...