0

I know some javascript but never quite understood why this code makes the buttons disappear.

<input type="button" name="clickable" value="Click me!" onclick="clicked();">

OR

<button onclick="clicked();">Clickity</button>

Here is my function

function clicked() {
    document.write("Thank you");
}

As you can see it is not telling the element to hide or anything like that. Can someone explain this? A solution would be nice.

JSBin

  • don't use document.write, its a bad practice and that's erasing your other stuff – juvian Apr 29 '14 at 00:41
  • okay, so document.write clears the screen –  Apr 29 '14 at 00:45
  • @unableToCompile, only after the document has been fully parsed. You can run that line in line with the regular flow of the document, but within function calls, it will erase everything. – Sunny Patel Apr 29 '14 at 00:52

3 Answers3

0

Because you write your document to "Thank you"

Try to use alert or console.log

jhyap
  • 3,779
  • 6
  • 27
  • 47
0

document.write overwrites the existing HTML on the page. You could try something like this:

Script:

function clicked() {
    document.getElementById('myOutput').innerHTML="Thank you";
}

HTML:

<input type="button" name="clickable" value="Click me!" onclick="clicked();">
<div id="myOutput"></div>
jake
  • 1,027
  • 8
  • 9
0

You executed document.write() after the DOM was loaded and ready, which writes over the HTML of the entire page. This SO Answer will help elaborate.

Community
  • 1
  • 1
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46