Michael
Michael

Reputation: 9402

How to override CSS style assigned to element

I've got a DIV covering the entire document:

<DIV style="position:'fixed';left:'0px';width:'100%';height:'100%';top:'0px',z-index:-20">

The zIndex of -20 is to prevent the DIV from coming up on top of other elements and interfering with mouse events.

However, when the page is busy with an asynchronous request, I want to bring the DIV to the top. My async request function sets the class of a user-defined variable element to "AJaXBusy" and then I style that class however I want. However, in this case, the style of "zIndex:100" isn't working, because the default value of -20 is overriding it!

Here's the code I'm using the show the DIV:

css('.AJaXBusy').backgroundColor="#ffddff"
css('.AJaXBusy').zIndex='100 !important'  

(The CSS function returns a style-sheet object style property, it's about 30 lines of code so I have omitted it.)

How do I get a CSS class definition to override the value that has been assigned directly to the element? I've read about specificity and inheritance, but it didn't seem to address effects applicable in the document itself.

Upvotes: 0

Views: 1132

Answers (3)

Leo
Leo

Reputation: 13858

If you use JS to set element style (i.e. ele.style.zIndex), then '100 !important' is not a legal value (while '100' is), so the expression silently fails.

However, if you use ele.setAttribute('style', '.....'), then !important could be applied.

And, inline style has much higher previledge than css class, so you cannot override it.


A much better approach would be, if you could edit HTML, use different class definitions.

<style>
    .undercover { z-index: -20; }
    .cover { z-index: 100; }
</style>
<div class="AJaXBusy undercover">

Then change class name when you want to make it

var ajaxBusy = document.querySelector('.AJaXBusy')
ajaxBusy.classList.remove('undercover')
ajaxBusy.classList.add('cover')

Upvotes: 2

tonesforchris
tonesforchris

Reputation: 303

As others have said, zIndex is how you update the property in javascript, elsewhere you refer to it as z-index.

I would recommend that instead of using a negative z-index to attempt to stop it interfering with the page, leave the z-index high, and hide the DIV using the css display:none; and only show the DIV when you want it to block page interaction (during AjaXBusy).

Upvotes: 0

chrismillah
chrismillah

Reputation: 3914

use !important after your declaration.

z-index:100 !important; 

Upvotes: 0

Related Questions