What is the problem with this JavaScript code? I'm trying to change the text of < H1 & gt; Element on click

advertisements

I just started learning JavaScript.

I'm trying to change the text on a click.What's wrong with this code. Please let me know. Thanks

<!DOCTYPE html>
<html>
<body>

<script>

function change_text(id)
{
 var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");

 var x = Document.getElementById("heading");

 for(var i=0;i<arr.length;i++)
  x.innerHTML=arr[i];

 x.style.visibility="hidden";

 }
</script>

<h1 onclick="change_text()" id="heading">Click on this text!</h1>
</body>
</html>


For one thing, you have two quotes here:

""oops! Once more!"

should be:

"oops! Once more!"

Document needs to be all lower-case (document).

change_text(id) is never used, and

x.style.visibility="hidden" needs to be moved outside the for loop.

You don't need a for loop at all, though, you just need to increment i++ every time the method is called, otherwise it will skip straight to "Goodbye".

<script>
var i = 0;
function change_text()
{
 var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");

 var x = document.getElementById("heading");

  i++;
  x.innerHTML=arr[i];
  if(i >= arr.length) {
        x.style.visibility="hidden";
  }

}

</script>

EDIT: EDIT2: OK, you got the idea before!