I want to show a button on my site but it should only be instantiated when JavaScript loads.
How do I do this?
<button>Click me!</button>
I want to show a button on my site but it should only be instantiated when JavaScript loads.
How do I do this?
<button>Click me!</button>
Keeep your button hiddden and show it at the time of dom ready.
<button style="display:none">Click me!</button>
then at
$(document).ready(function () {
$("button").show()
});
document.ready will fire only after loading all the elements including scripts.
Use a function and initialize it at the end of your script and keep the DOM as @AnoopJoshi suggested
<button id = "button1" style="display:none" >Click me!</button>
and script would be
function init(){
document.getElementById("button1").style.display = 'block';
}
init();
One way to do that is using either document.onload
or window.onload
and add the button to your document.
<script language="javascript">
window.document.onload = function(e){
//add or show button
}
window.onload = function(e){
//add or show button
}
</script>
If the client does not have javascript it will not execute. The difference between window.load
and document.load
is that the first waits for everything to be loaded while the latter only waits for the DOM to be ready.
Many people prefer jquery to check for document ready with
$(document).ready(function() { /* your code */ });
You can add the button using javascript like this (assuming you want to add it to a div with id=myDiv
.
var div = document.getElementById("myDiv");
var abutton = document.createElement('button');
abutton.innerHTML = "your text";
mydiv.appendChild(abutton);