-6

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>

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

3 Answers3

2

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.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • 2
    Downvoter: comment or your downvote is completely useless to everybody – mplungjan Nov 27 '15 at 07:15
  • @mplungjan they do that all the time – guradio Nov 27 '15 at 07:24
  • 1
    @mplungjan I am not the downvoter but a problem might be with this code is that the button is still in the DOM. – Niki van Stein Nov 27 '15 at 07:25
  • @BasvanStein thats a good point. anyway lets wait for the downvoter to comment the reason. – Anoop Joshi P Nov 27 '15 at 07:27
  • 2
    @AnoopJoshi upvoted you, it is exactly the same as the late accepted answer. Why that one is accepted... no clue. Only difference is js vs jquery. – Niki van Stein Nov 27 '15 at 07:48
  • 2
    @BasvanStein thanks man. I was about to comment the same thing. OP doesn't have any manners to comment/read the other answers. Didn't expect such a behaviour from the user who got more than 1k reputation. – Anoop Joshi P Nov 27 '15 at 07:51
  • @AnoopJoshi My apologies. In my pursuit for the quickest fix, I used Vasu's code. I've actually found another solution using the js/no-js class in my head element. I'm going to post my answer shortly :) – michaelmcgurk Nov 27 '15 at 09:25
2

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();
Vasu Sheoran
  • 215
  • 1
  • 6
1

Javascript onload

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.

jQuery ready

Many people prefer jquery to check for document ready with

$(document).ready(function() { /* your code */ });

Add element using Javascript

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);
Community
  • 1
  • 1
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62