Okay so In my last question it said to make my variables into strings which I did but it still doesn't work, as I sad before the point of this is tohave the prompt coe up where a user will set there mood from 1-10. If they pick between 1-3 the image will be sadface, 4-7 neutral face, and 8-10 happy face. but it isn't working the prompt shows up but it still does not work the javascript has been placed within the header:
</head>
<script>
var sad = "1",
sad2 = "2",
sad3 = "3";
var n1 = "4",
n2 = "5",
n3 = "6",
n4 = "7";
var h1 = "8",
h2 = "9",
h3 = "10";
var x = prompt("What is your mood from 1-10? 1 being sad, 10 being Happy.");
if (x === sad || x === sad2 || x === sad3){
document.getElementByTagName("img").src = "sad.png";
document.getElementById("msg").innerHTML = "Sad.";
document.getElementById("msg").href = "http://www.sad.com";
}
else if (x === n1 || x === n2 || x === n3 || x === n4){
document.getElementByTagName("img").src = "sad.png";
document.getElementById("msg").innerHTML = "Neutral.";
document.getElementById("msg").href = "http://www.neutral.com";
}
else if (x === h1 || x === h2 || x === h3){
document.getElementByTagName("img").src = "happy.png";
document.getElementById("msg").innerHTML = "Happy.";
document.getElementById("msg").href = "http://www.happy.com";
}
</script>
</head>
<body style="text-align:center">
<img src="neutral.png">
<h1><a id="msg" href="">Waiting...</a></h1>
</body>
Please tell me what I'm doing wrong here everything comes with no errors but my output the image stays neutral if some can try this project and test it and prove it works please send me the code.
First of all, you're trying to access the DOM (document object model) before the page has loaded, so no HTML is live yet. In other words, you're interacting with a blank page. You'll have to put the script before the </body>
tag (which ensures that all HTML above the <script>
tag is live and has been updated in the DOM) or check that the page has loaded.
The second issue I see here is that you're using a function that doesn't exist: getElementByTagName
. The function is getElementsByTagName
, and it returns an HTMLCollection. This is an array-like object, so you'll have to access the img
element you're targeting by document.getElementsByTagName('img')[0]
.
The two changes above should make the script run like you want it to, but I'm going to suggest another revision. Instead of processing the input as a string, I would parse it as an integer first and then check for that integer's inclusion in a given range. For example:
var x = prompt( "What is your mood from 1-10? 1 being sad, 10 being Happy." );
x = parseInt( x );
if ( x <= 3 ) {
// sad :(
} else if ( x <= 7 ) {
// neutral :|
} else if ( x <= 10 ) {
// happy :)
}
Above, I prompt the user, and then convert the input to an integer. To check which emotion to return, I use the <=
comparison operator.