Reputation: 1016
I have a button in my page
<button onclick="document.getElementById('donation').style.visibility='visible'">Support</button>
That I want to have linked to making a hidden div (donation) visible. I'm not sure if the getElementById works with divs, but I couldn't find out either, because when I changed the Id to h1, with a simple color change for style, it didn't work either. Is there a problem with my button or syntax?
Upvotes: 1
Views: 573
Reputation: 90068
In order for document.getElementById('donation')
to return a DOM
element this condition would need to be true
html
element and only one with id="donation"
in your page. For example: <div id="donation"></div>
It's possible that your function works flawlessly (you can easily tell if it is by looking at your browser console
after you pushed the button) but your element would still remain not visible. For example, if its display
property is set to none
. There are many possible reasons why an element might not be rendered by the browser. The fastest way to pinpoint the reason would be for you to create a minimal, complete and verifiable example (using the <> button) where we could experience the issue.
Upvotes: 1
Reputation: 502
For me, I think separating the codes will keep things clearer and readable.
<button id="donation_btn">Support</button>
The javascript
function enableDonation( button, donationElement ) {
// check if the button is defined
if ( button != undefined
&& button != null ) {
button.addEventListener( "click", function () {
donationElement.style.display = "block";
});
}
// execute the code on document load
window.addEventListener( "load", function () {
enableDonation(
document.getElementById( "donation_btn" ),
document.getElementById( "donation" )
);
});
Upvotes: 0
Reputation: 286
You can still work this with an inline onclick.
Andrei is correct about the id needing to be an individual.
<button onclick="document.getElementById('donation').style.visibility='visible'">Support</button>
<div style="background-color: gray; width: 50px; height: 50px; visibility: hidden;" id="donation"></div>
Technically though, it's better to keep your css and javascript in the head tag or outside of the html.
Upvotes: 1