Reputation: 5450
I have a page with a fixed position 'go to top' <a>
which sticks to the bottom of the page as the user scrolls. It's in the footer DIV of the page like so:
.pagedown div a { position: fixed; margin-left: 8px; margin-top: 50px; width: 44px; height: 40px; color: #bd1300; background: none;}
<div class="footer"><a id="gototop" title="Go to top!" href="#">^</a></div>
Using jQuery or JS I would like to be able to change the color of the <a>
based on the true underlying background color. So far, I've looked here:
How do I detect the inherited background-color of an element using jQuery/JS?
This code doesn't seem to work for my use case. Perhaps since the <a>
in question is not really 'inside of' the rest of the page DOM as it scrolls by?
So: is there a way to detect the -true- underlying background color (ie. the background color the user would actually see in the viewport)?
Upvotes: 2
Views: 2959
Reputation: 5428
You're looking for window.getComputedStyle
.
It returns the computed style of the element you give it.
EDIT: The background color property was returning transparent, so I wrote a recursive background color search function that circumvents this behavior.
function getBGColor(el) {
var s = getComputedStyle(el),
b = s.backgroundColor,
e = el;
if ((b === "transparent" || b === "rgba(0, 0, 0, 0)" || b === "rgba(255,255,255,0)") && e.parentNode !== null)
b = getBGColor(e.parentNode);
return b;
}
document.getElementById("o").innerHTML = "Background Color: " + getBGColor(document.getElementById('gototop'));
html,
body {
background-color: lavender;
}
a {
color: #bd1300;
}
<div>
<a id="gototop" title="Go to top!" href="#">^</a>
</div>
<div id="o"></div>
Upvotes: 1
Reputation: 115010
Support is not great (no IE) but you can use CSS for this.
.footer {
font-size: 72px;
text-align: center;
margin-bottom: 10px;
line-height: 100px
}
a {
color: white;
mix-blend-mode: difference;
}
body {
background: red;
}
<div class="footer"><a class="gototop" title="Go to top!" href="#">^</a>
</div>
.footer {
font-size: 72px;
text-align: center;
margin-bottom: 10px;
line-height: 100px
}
a {
color: white;
mix-blend-mode: difference;
}
body {
background: blue;
}
<div class="footer"><a class="gototop" title="Go to top!" href="#">^</a>
</div>
Upvotes: 3