The CSS transition fails to function correctly once a specific function is executed

When I hover over a div, the background color changes due to a transition effect. However, if I click on a button that triggers myFunction2 to change the background color of the div before hovering over it, the transition effect no longer works.

function myFunction2() {
  document.getElementById("myDIV").style.backgroundColor = "yellow";
}

function myFunction() {   
  document.getElementById("myDIV").style.WebkitTransition = "all 2s"; // Code for Safari 3.1 to 6.0
  document.getElementById("myDIV").style.transition = "all 2s";     // Standard syntax
}
#myDIV {
      border: 1px solid black;
      background-color: lightblue;
      width: 270px;
      height: 200px;
      overflow: auto;
    }
    
    #myDIV:hover {
      background-color: coral;
      width: 570px;
      height: 500px;
      padding: 100px;
      border-radius: 50px;
    }
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <p>Mouse over the DIV element and it will change, both in color and size!</p>
    <p>Click the "Try it" button and mouse over the DIV element again. The change will now happen gradually, like an animation:</p>
    <button onclick="myFunction2()">Try it2</button><br>
    <button onclick="myFunction()">Try it</button>  
    <div id="myDIV">
      <h1>myDIV</h1>
    </div>
  </body>
</html>

Answer №1

When using myFunction2(), the background color of the div is set to yellow, preventing any further change (i.e., the transition will no longer modify the background color).

If you desire a transition effect, you can add the transition through JavaScript itself.

DEMO:

<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {
  border: 1px solid black;
  background-color: lightblue;
  width: 270px;
  height: 200px;
  overflow: auto;
}

#myDIV:hover {
  background-color: coral;
  width: 570px;
  height: 500px;
  padding: 100px;
  border-radius: 50px;
}
</style>
</head>
<body>

<p>Mouse over the DIV element and it will change, both in color and size!</p>

<p>Click the "Try it" button and mouse over the DIV element again. The change will now happen gradually, like an animation:</p>
<button onclick="myFunction2()">Try it2</button>
<br>
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
  <h1>myDIV</h1>
</div>

<script>
function myFunction2()
{
 document.getElementById("myDIV").style.backgroundColor = "lightblue";
var css = '#myDIV:hover{ background-color: yellow !important;}';
var style = document.createElement('style');
if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

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



function myFunction() {
var css = '#myDIV:hover{ background-color: coral !important;}';
var style = document.createElement('style');
if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

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

  document.getElementById("myDIV").style.WebkitTransition = "all 2s"; // Code for Safari 3.1 to 6.0
  document.getElementById("myDIV").style.transition = "all 2s";     // Standard syntax
}
</script>

</body>
</html>

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

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

How can I display a nested div when the parent div's v-if condition is not met?

In my project, I am utilizing Laravel 6 in combination with Vue.js 2. To iterate through users and showcase their information within div elements, I am using a for loop outlined below. The Category names are stored in user.pivot.demo2, and the users are ...

When utilizing the --watch flag, Node-sass will fail to function properly

Encountering an issue with the "--watch" or "-w" flag when running node-sass. After installing node-sass as a devDependency and setting up a script to compile SCSS code, everything runs smoothly without any flags. However, adding the "--watch" flag causes ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

Maximizing Bootstrap's Potential: Achieving Right Alignment for Divs

I am facing a challenge with aligning my div in the layout_cshtml. Currently, it is aligned to the left and the search bar and dropdownlist are not displaying properly. This negatively impacts the user experience. Additionally, my navigation menu is not ...

What steps should I take to modify the URL using the SELECT tag?

Having a bunch of SELECT tags in place <select id="url"> <option id="url1" >url 1</option> <option id="url2" >url 2</option> </select> <button onclick="go()">GO</button> Followed by the associated scrip ...

Ways to remove scroll bars from a textarea in JavaFX

Is there a way to disable the scrollbars on a TextArea element? I managed to remove the horizontal scrollbar by using: TextArea.setWrapText(true); However, I am struggling to disable the vertical scrollbar - all I can do is hide it. My goal is to hav ...

Download personalized HTML design

Situation When exporting to HTML, the resulting code appears as follows: <html> <head> <title></title> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <style type="text/css" ...

How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method: var range = window.getSelection (); However, how can we obtain the style of this selection? For example, when I select bolded text or italicized ...

The div element on my website spans the entire width, yet it appears slightly narrower than the body

My website features a scrolling div element that spans 100% of the screen, but I am encountering an issue with slight horizontal scrolling and the background image extending beyond the visible area. I am striving to adjust the width of the div so that it ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

Bind a collection of Firestore documents dynamically using Vuexfire

I currently have a collection of firebase documents stored in a vuex state that is dynamically updated. My goal is to bind these documents with vuexfire dynamically as they are added or removed from the list. state: { docsToBind: [], // This array is dy ...

How can you create a scenario in Angular Material where items in a toolbar transition to the second line exclusively on mobile screens?

Visit the Angular Material website to see how the toolbar appears on a desktop: https://material.angular.io/ https://i.sstatic.net/KPFMv.png On mobile devices, the menu items Components, CDK, and Guides are displayed on the second line, while github, the ...

What issues could arise from utilizing PHP for generating variables within my CSS file?

One major limitation of CSS is the absence of variables. It would be beneficial to have the ability to use variables for controlling things like the location of imported CSS and color schemes within a design. An alternative solution could involve using a ...

Error message in React JSX file: "Encountered an issue with 'createElement' property being undefined"

In the file test_stuff.js, I am executing it by using the command npm test The contents of the file are as follows: import { assert } from 'assert'; import { MyProvider } from '../src/index'; import { React } from 'react'; ...

Is it possible to align text to an image within an input text field?

<input type="text" class="usernm" style="color:black;font-weight: bold;outline-width: 0;" id="username" /> I have a question about styling HTML. I am attempting to include an icon inside a text field, but I'm strugglin ...

Babel: deactivate transpilation of import directives

Currently, I am facing a unique challenge with the babel transpiler in my project. The issue is that I am working with an ES5 JavaScript codebase that already includes imports and export directives. For instance: import Widget from 'component:compon ...

AngularJS redirection causes the previous template to quickly appear and then disappear

This particular question has been circulating without a satisfactory resolution for some time, so hopefully the information provided here will help clear up any confusion. Essentially, I have an object called resolve attached to my routes, set up like thi ...