So, though you are using visibility: hidden
, I would recommend using opacity
instead. This still hides the button as you would expect. Feel free to look into the W3 Schools website. It has a lot of great resources that cover simple things like this.
I utilized the following references from that site:
onclick Event
onmouseover Event
onmouseout Event
opacity Property
function OnHover(element) {
element.style.opacity = 100;
}
function OnExit(element) {
element.style.opacity = 0;
}
function OnClick(element) {
element.innerHTML = "You clicked me as a hidden button!";
element.style.color = "red";
}
.btn {
visibility: hidden;
}
.btn:hover {
visibility: visible !important;
}
<button id="btnO" onmouseover="OnHover(this)" onmouseout="OnExit(this)" onclick="OnClick(this)" style="opacity: 0;">Opacity</button>
<button id="btnV" onclick="OnClick(this)" class="btn">Visibility</button>
I believe since visibility has been set to hidden
in your scenario, the page doesn't fire the events wired into the element. Even CSS selectors such as hover
seem to be impacted by this property. It doesn't appear to reduce the size of the element, as changing an element's visibility
via developer tools in live time doesn't affect the layout of the page. However, opacity
simply reduces the alpha channel on the element and all events are still fired off as normal.
More senior web developers; feel free to correct me if I'm wrong in the above statement. I couldn't find much documentation on this.
Tip: Hidden elements take up space on the page. Use the display property to both hide and remove an element from the document layout!
With respect to the quote above from W3 Schools, you could create an empty div
element that houses your button. Then, when the user hovers over the div
element display the button or call a javascript function from the onclick
event. In which case you could use the visibility
property as you wouldn't be directly interacting with the button, but rather the div
.