javascript dice game - image does not change - javascript

Having a slight issue calling a math.random image for a dice game. When I click the roll button the image does not change. I have the images saved where the .html file is. Any help is much appreciated!
Roll The Dice
<script type="text/javascript">
var dieImage;
function start()
{
var button = document.getElementById(rollButton);
button.addEventListener("click", rollDice, false);
dieImage = document.getElementById("die1");
}
function rollDice()
{
setImage(dieImage);
}
function setImage(dieImg)
{
var dieValue = Math.floor(1 + Math.random() * 6);
dieImg.setAttribute("src", "die" + dieValue + ".jpg");
dieImg.setAttribute("alt", "dieImg with" + dieValue + "spots");
if (dieValue == 6)
{
document.getElementById("sometext").innerHTML = "You Win!";
}
else
{
document.getElementById("sometext").innerHTML = "Roll Again";
}
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<form action = "#">
<input id = "rollButton" type = "button" value = "Roll Dice">
</form>
<li>
<img id = "die1" src = "die1.jpg" alt = "blankImage">
</li>
<div id = "sometext">Roll for a 6!</div>
</body>

The only issue with the code above is this line:
var button = document.getElementById(rollButton);
Should read
var button = document.getElementById("rollButton");
The above change DOES cause the function to work, and the image to be updated. Assuming all of your images are in fact in the right place, you will see them change.
As a note of encouragement, I would suggest you code in Firefox, and get Firebug. With these tools, you can then utilize the Firebug console and/or Firefox's Web Developer Error Console. These are tremendously useful for troubleshooting problems like this quickly.

Related

How do you save a state in HTML?

As you might know from my previous posts, I am developing a chrome extension. I have a button that toggles the extension on & off, and this button's state is saved when you click out of the extension. You can see the code for this below:
popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="StyleSheet" type="text/css" href="style_popup.css"/>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div class="navbar">
View My Dashboard
</div>
<h1 class="center">[Title]</h1>
<button id="buttonclick" class="button">Enable Control</button>
<br> <img src="green_circle.PNG" height="140" width="150" id="centerimage"> <br>
<p class="center" id="status"> [Title] is running! </p>
</body>
</html>
popup.js
let changeColor = document.getElementById('changeColor');
chrome.storage.sync.get('color', function(data) {
changeColor.style.backgroundColor = data.color;
changeColor.setAttribute('value', data.color);
});
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('buttonclick');
// onClick's logic below:
link.addEventListener('click', function() {
handler();
});
});
function handler()
{
chrome.storage.local.get({count: 0}, function (result) {
var count = result.count;
var buttonState = document.getElementById('buttonclick');
var imageState = document.getElementById('centerimage');
var status = document.getElementById('status');
if (count == 0) {
buttonState.style.backgroundColor = "#75ad0a";
buttonState.innerHTML = "Enabled";
imageState.src = "green_circle.PNG";
status.innerHTML = "[Title] is running!"
count = 1;
}
else {
buttonState.style.backgroundColor = "#AA2B0E";
buttonState.innerHTML = "Disabled";
imageState.src = "red_circle.png";
status.innerHTML = "[Title] is not running!"
count = 0;
}
chrome.storage.local.set({count: count});
});
}
However, I am running into a bit of a pickle. I want to make it such that if a user were to click the button (thereby disabling the extension), exit the chrome extension, and then click back into it, it would still show as disabled. With my current case, however, it will just display the "Enable Control" and "[Title] is running" every time they open the extension UNTIL the user clicks the button. In other words, it would be reset & and I want the state to be preserved. As you can see from my popup.js, I've already written code that saves the state of a variable, but I am unsure how to actually make the state be preserved in the HTML. I would greatly appreciate any help, thanks!

The value of input element changes but not shown in the browser(s)?

I wrote a live search field for a part of my form, when the suggestions come and user clicks on one of them, a js function (selectedService) is being called to get the innerHTML of the li which the user clicked on!
everything works perfectly when you look at the code in 'Inspect Element' of the browser, but not on the web page!
after the user clicks on the on the suggestion the value property of input element changes in the code but on the browser. the content of input field is still what the user is typing in it.
here's the code :
<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="UTF-8">
</head>
<body>
<input value="" id="services" placeholder="click or type plz..."/>
<ul id="suggestions">
</ul>
<style>
/* some styles */
</style>
<script>
var input = document.getElementById("services");
var suggestions = document.getElementById("suggestions");
input.oninput = function() {
var q = input.value;
if (q.length < 2) {
suggestions.setAttribute("style","display: none");
return;
}
var xhr2 = new XMLHttpRequest;
xhr2.open("GET", "theURL/service-request-handler.php?q="+q, true);
xhr2.onreadystatechange = function() {
if (xhr2.readyState == 4 && xhr2.status == 200)
{
var result = xhr2.responseText;
console.log("server response = "+result);
var json = JSON.parse(result);
showSuggestions(json);
}
};
xhr2.send();
};
function showSuggestions(json) {
suggestions.setAttribute("style","display: block");
var li_list = '';
var i = 0;
for (i=0; i<json.length; i++)
li_list += '<li id="'+i+'" onclick="selectedService('+i+')">'+json[i]+'</li>';
suggestions.innerHTML = li_list;
}
function selectedService(i) {
li_target = document.getElementById(i);
console.log(li_target.innerHTML);
// input.innerHTML = li_target.innerHTML;
input.setAttribute("value",li_target.innerHTML);
suggestions.setAttribute("style","display: none");
}
</script>
</body>
</html>
the result in the Inspect Element :
I'd appreciate any help or suggestions :)
input.value = li_target.innerHTML
You can set value property directly:
input.value=li_target.innerHTML;
Probably you are using firefox browser, you should use this to work in both, chrome and firefox.
input.value = li_target.innerHTML;
This happens because property and attributes are different.
Attributes are defined on the HTML markup but properties are defined on the DOM.
You can use jQuery UI for autocomplete search.

Automatically load next image from array everytime user enters website

So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}

Having Trouble Switching Images

I'm just learning some java. I am currently learning if, else statements.
In the game I am creating, the user picks a number between 0 and 10 and puts it into an input box. If correct, the image on screen changes to one picture, if incorrect, it switches to a different picture. However, I cannot seem to get the images to change at all. I've tried a few different ways of coding; I'm currently using an img array. However, when I do the code I receive an ObjectHTMLImageElement error.
Here is my current code:
<div id="top">
<h1>Pie in the Face</h1>
<p>Guess how many fingers I'm holding up between 0 and 10.
<br /> If you guess correctly, I get a pie in the face.
<br /> If you guess wrong, you get a pie in the face.</p>
<input id="answer" />
<button id="myButton">Submit</button>
</center>
</div>
<div id="container">
<div id="image"></div>
<div id="manpie"></div>
<div id="girlpie"></div>
</div>
<script type="text/javascript">
var x = Math.random();
x = 11 * x;
x = Math.floor(x);
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/manpie2.jpg";
imgArray[1] = new Image();
imgArray[1].src = "images/girlpie2.jpg";
document.getElementById("myButton").onclick = function() {
if (x == document.getElementById("answer").value) {
document.getElementById("image").innerHTML = imgArray[0];
// what I had document.getElementById("image").innerHTML=imgArray[0];
} else {
document.getElementById("image").innerHTML = imgArray[1];
}
}
</script>
</body>
I have also tried using lines such as: document.getElementById("image").innerHTML=document.getElementById("manpie");
and then nothing works. Here is a link to the "live" site it's on.
http://176.32.230.6/mejorarcr.com/
any help would be appreciated. Thank You!
You have to change the innerHTML value in your code:
if (x==document.getElementById("answer").value) {
document.getElementById("image").innerHTML='<img src="'+imgArray[0].src+'" />';
// what I had document.getElementById("image").innerHTML=imgArray[0].src;
} else {
document.getElementById("image").innerHTML='<img src="'+imgArray[1].src+'" />';
}
DEMO or this
change:
document.getElementById("image").innerHTML=imgArray[0];
to:
document.getElementById("image").setAttribute("src", imgArray[0]);
make sure imgArray[0] is the actual image path:
imgArray[0]="images/manpie2.jpg";
imgArray[1]="images/girlpie2.jpg";

Is there a way that you can print this code instead of having an onclick?

I am making a puzzle website where you select a puzzle, I was wondering if there was a way of, instead of it being in pop up boxes it would be printed to the website. I don't mind what code we are using as I am fluent in most,
This is the code I have so far:
<body>
<script type="text/javascript">
function myFunction()
{
function ask() {
var a = (Math.round(Math.random()*1000000))
alert (a)
return prompt("What was the number?") == eval( a );
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction()">Remember the number</button>
</body>
<body>
<script type="text/javascript">
function myFunction2(){
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction2()">Quick math</button>
</body>
</html>
</html>
So I was wondering if there was a way to make it show up as text and have a text box on the page to type into that would still work. And the design is able to be changed, so I can make a larger text box, or a larger font so it's not just an un-editable onclick.
All help greatly appreciated.
Thanks.
I did what I thought that you wanted to the "Remember the number" button click.
Sorry, had no time to do the other one.
HTML:
<body>
<button id="rmbrBtn">Remember the number</button>
</body>
<body>
<button id="quivkBtn">Quick math</button>
<div id="question_area">
</div>
</body>
</html>
</html>
JS & jQuery code:
$("#rmbrBtn").click(function()
{
// Answers collection
var questions = [];
// Check the correctness of the answer
function checkAnswer (){
total = questions.length,
correct = questions.filter(Boolean).length;
if(total < 5)
{
ask();
}else{
var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
$("#question_area").append(answer);
$("#ansOk").click(function(){
$(this).parent().empty();
$(this).parent().remove();
});
}
}
// Get the question
function ask() {
var a = (Math.round(Math.random()*1000000));
// View the generated number
var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';
// Prompt user with a text box
var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input type="button" id="prmtOk" value="Ok"/></div>';
// Append
$("#question_area").append(viewNumber);
$("#ok").click(function(){
$(this).parent().empty();
$(this).parent().remove();
$("#question_area").append(promptVal);
$("#prmtOk").click(function(){
var prmt = $("#ans").val();
var addVal = prmt == a;
questions.push(addVal);
checkAnswer();
$(this).parent().empty();
$(this).parent().remove();
});
});
}
// Run the function.
checkAnswer();
});
Online solution:
JSFiddle
Try to do the other one same as this.
Sorry had no time to comment also.
I think you can figure this out.
Just add a div at the top of your page and use jqueries .html() and you will be done
like
$('.header').html('You are correct.');
here is a fiddle http://jsfiddle.net/AMISingh/8nWKD/3/
This can also be done without JQuery and just JavaScript.
http://jsfiddle.net/8nWKD/4/
<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>
and the JavaScript
function test_click()
{
document.getElementById("header").innerHTML = "CORRECT!";
}

Categories

Resources