Reputation: 36564
I am making a monopoly board in which each block is an element. I need to make the blocks dull and bright based on different conditions. To change brightness I use filter
property. The brightness will be changed dynamically so I need to change style.filter
.
Now there are other properties like 'drop-shadow'
which I want to be constant and I have used them in css file. But now the problem is that these both filters can't exist in one time. Is there any way to combine both style.filter
and filter
property in css.
document.querySelector('#test').style.filter = 'brightness(0.5)'
div{
height:100px;
width:100px;
border:2px solid;
background:orange;
filter:drop-shadow(2px 4px 6px black);
}
<div id="test"></div>
In the above script I need to show both brightness
and drop-shadow
but only brightness is working.
Note: In the example I just told about two properties but in my real code there are more. I know this can be solved by creating a constant string for css properties and then each time concat it to style.filter
. But I don't want that.
Upvotes: 2
Views: 467
Reputation: 272771
Use CSS variables:
document.querySelector('#test').style.setProperty("--b", "0.2");
div#test{
height:100px;
width:100px;
border:2px solid;
background:orange;
filter:drop-shadow(2px 4px 6px black) brightness(var(--b,1)) blur(2px);
}
<div id="test"></div>
Upvotes: 3
Reputation: 346
function setBrightness( element, val ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ) prop = 'brightness(1)';
prop = prop.replace( /brightness\(\d+(\.\d+)?\)/g, `brightness(${val})` );
element.style.filter = prop;
}
Upvotes: 1
Reputation: 346
If you set a filter property, you rewrite all its string, not appending into it. So you need to make some variable to store all filter properties. It can be an array for exaple. Then push or splice your properties in that array, and update filter with the result. For example:
let arr = [];
arr.push('brightness(0.5)');
arr.push('drop-shadow(2px 4px 6px black)');
and then update filter property:
document.querySelector('#test').style.filter = arr.join(' ');
Another way is to write the function that will get filter string, convert it into an array, and then do the same thing as above.
To combine both CSS and element.style.filter, you can try something like this:
function addFilter( element, filterValue ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ){
element.style.filter = filterValue;
} else {
let arr = prop.split(' ');
if( arr.includes(filterValue) ) return;
arr.push(filterValue);
element.style.filter = arr.join(' ');
}
}
function removeFilter( element, filterValue ){
let prop = getComputedStyle( element ).getPropertyValue('filter');
if( prop === 'none' ) return;
let arr = prop.split(' '),
index = arr.indexOf(filterValue)
if( index !== -1 ) arr.splice( index, 1 );
element.style.filter = arr.join(' ');
}
Upvotes: 2