What is the correct linear-gradient (CSS) syntax in Javascript?

Asked

Viewed 132 times

1

I’m trying to manipulate a background with onmouseover/onmouseout and I came across the following question:

How the CSS syntax below would look in Javascript?

background-image: linear-gradient( to top, rgba(23,35,34,0.55), transparent);

I’ve tried this, among other variations but I couldn’t make it work...

var barra_off = document.getElementById("idboxControl");

function func_barra_off(){

barra_off.style.backgroundImage ="linearGradient( to top,rgba(23,35,34,0), transparent);"

barra_off.style.webkitTransition ="0.5s ease-out";

}

Someone?

2 answers

2


The mistakes are:

  • Instead of linearGradient, would be linear-gradient. The camelCase is only in the Javascript property, the value has the same syntax used in CSS.
  • Cannot contain the semicolon at the end of the value, otherwise the value becomes invalid.

Seria:

barra_off.style.backgroundImage = "linear-gradient( to top,rgba(23,35,34,0), transparent)";

An example of changing the rgba alpha channel to 1 to be able to view the effect:

var barra_off = document.getElementById("idboxControl");

function func_barra_off(){
   barra_off.style.backgroundImage ="linear-gradient( to top,rgba(23,35,34,1), transparent)"
   barra_off.style.webkitTransition ="0.5s ease-out";
}
#idboxControl{
   width: 200px;
   height: 200px;
   border: 1px solid #000;
}
<div id="idboxControl" onmouseover="func_barra_off()">
   passe o mouse
</div>

  • Thanks Sam! Super didactic your explanation. Solved :D

2

The syntax is exactly the same as the one you used in CSS, because the HTMLElement.style work with the same syntax used by the styles inline element. The detail is that you should not pass the semicolon at the end:

const div = document.querySelector('div');

div.style.height = '100px';
div.style.backgroundImage = 'linear-gradient( to top, rgba(23,35,34,0.55), transparent)';
<div></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.