I am building a small library of floating notifications on the page and the problem arose, since on the page where I will use it there are various floating elements such as modals and buttons from third-party plugins.
A first solution would be to use a high value so z-index
let's say:
.floating-notification {
z-index: 10000;
}
But the problem is that being a fixed number does not assure me that it is the largest, since someone in a third-party library may have thought of a larger number, let's say 10001 , so if both components are shown together, the one created will be shown below.
Another forced solution would be to use the maximum admissible value for z-index
but this varies according to the browser and is not standard.
The question is if there is any way to know of all the elements of the DOM which is the maximum value of the z-index attribute.
The following statement:
And the following question:
They are not entirely compatible. It is not necessary to find the maximum
z-index
of the entire document, since itz-index
defines a stacking context .Two elements belonging to different stacking contexts cannot be compared by their
z-index
Consider the following example, taken from the MDN network:
In it, you can see that even though it
DIV #4
has az-index: 6
, it is not drawn on itDIV #1
withz-index: 5
Then, you are only interested in direct child nodes from the node you want to draw your content on.
A code that would help you to do this is the following:
You can test it in the following snippet:
There's no elegant way to do this, you'll have to look at all the elements and stick with the highest z-index:
There is no native function or anything like that, you have to do it by hand. I leave you the example in Jquery, because you already have one in Javascript, with which you are more comfortable.