I'm learning as I go through this project; apologies if I've overlooked the obvious.
My goal: a button over an image; this button runs a javascript function to select a random quote from an array and display it. So far, so good.
The problem: The displayed quote makes both image and button vanish.
Most examples I've found in my searching have improper use of .write as the issue. I have yet to find someone with precisely my problem. I do know now to avoid that, though! I tried following up my code with a div that had the variable as an id, to no avail. I also just tried moving things around with line breaks. I'm at a loss after some hours of Googling.
I've not touched CSS yet. My javascript is as follows:
var spark = [
"Sample 1",
"Sample 2",
"Sample 3",
]
function newSpark() {
var randomNumber = Math.floor(Math.random() * (spark.length));
document.getElementById('sparkDisplay').innerHTML = spark[randomNumber];
}
and my pertinent HTML, first in the head, then in the body:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 100%;
max-width: 400px;
}
.container img {
width: 100%;
height: auto;
}
.container .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
background-color: rgb(0, 0, 0);
color: rgb(227, 240, 48);
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 5px;
text-align: center;
}
.container .btn:hover {
background-color: black;
}
</style>
<h2>Jar of Sparks</h2>
<script src="javascript.js"></script>
<div id="sparkDisplay">
<img src="jarpic.jpg" alt="a jar of fireflies in a starless night" style="width:100%">
<button onclick="newSpark()" >grasp a spark</button>
</div>
Any pointers to put me on the right track would be most appreciated!
CodePudding user response:
In this line
document.getElementById('sparkDisplay').innerHTML = spark[randomNumber];
you are replacing the both image and the button which are also using sparkDisplay
element with your quote, it is better to create a new div and add that quote to it.
CodePudding user response:
The problem is that you are calling the innerHTML on #sparkDisplay. If you move the button and img outside of the div with id sparkDisplay the button and img will then be consistant.
<div id="sparkDisplay">
</div>
<div jarpic.jpg" alt="a jar of fireflies in a starless night" style="width:100%">
<button onclick="newSpark()" >grasp a spark</button>
</div>