dynamic content


You know what's cooler than alerting? Changing stuff on the page.

Check this out:

<p>My name is <span id="name">John</span></p>

<button onclick="changeName()">Change Name</button>

<script>
function changeName(){
  var name = prompt("What's your new name?");
  document.getElementById("name").innerHTML = name;
}
</script>

My name is John

document.getElementById("name") means "get me the element with an id equal to name (which is our <span id="name">.

The next part, .innerHTML = name, means "set the stuff inside of the thing to the left to whatever is in the variable called name" (which is holding what we got from prompt). Pretty cool, right?

innerHTML

You can put any HTML in innerHTML that we've learned. Even things like images!

<button onclick="showCat()">Show me a cat</button>
<div id="catHolder">No cat here :(</div>

<script>
function showCat(){
  document.getElementById("catHolder").innerHTML = `<img src="https://res.cloudinary.com/genco/image/upload/v1496887393/kitten-looking-at-camera-521981437-57d840213df78c583374be3b_grg0sm.jpg" width='300px' />`;
}
</script>

No cat here :(

If you use backticks (`) instead of quotation marks (\' or \") you can use either quoting style in your HTML and won't mess it up.

Protip: include variables in backticked strings (for cleaner code) like this:

var url = "https://res.cloudinary.com/genco/image/upload/v1496887393/kitten-looking-at-camera-521981437-57d840213df78c583374be3b_grg0sm.jpg";
document.getElementById("catHolder").innerHTML = `<img src="${url}" width='300px' />`;

Resources


Challenge

Make a website that hides some secret content. If your visitor enters the correct password, show them some cool stuff. If they enter the wrong password, insult them for not knowing the password.


Solutions

Try this challenge on your own first, then come back here to see other people's solutions.

Try this challenge on your own first, then come back here to see other people's solutions.