Click here to Skip to main content
15,887,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I'm very new to coding... I want the answer to the question to show only after the person clicks on the button. At the moment the answer shows when the page loads, if you click show answer it hides the answer, and press again to show answer, but i want it to start by not showing answer (so not to give it away). All help welcome.

What I have tried:

BUTTON.button {
display: block;
margin-left: auto;
margin-right: auto;
align: centre }
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: #65a83d;
margin-top:20px;
}

<button class="button" onclick="myFunction()">Show Answer </button>
<div>
<div id="myDIV" class="hidden">
The answer is 10.
</div>

<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
Posted
Updated 26-May-17 8:17am

If you look at what the code is doing to show it, it is setting a style on the div. So, just do this to your div:
HTML
<div id="myDIV" class="hidden" style="display: none;">

and that will start it off hidden.
 
Share this answer
 
Firstly, you don't have a CSS class for "hidden"; so it won't do anything. To write the least amount of code to accomplish your needs, you need to call JavaScript MyFunction() either in the body or window onload(). I decided to do it in the body.

All I added was <body onload="myFunction()"> to the HTML body tag below.

Below is a sample web page to test it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>asdf</title>
<style type="text/css">
BUTTON.button {
display: block;
margin-left: auto;
margin-right: auto;
align: centre }
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: #65a83d;
margin-top:20px;
}
</style>
</head>
<body onload="myFunction()">
<button class="button" onclick="myFunction()">Show Answer </button>
<div>
<div id="myDIV" style="hidden">
The answer is 10.
</div>

<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900