Outputting a picture based on a variable's number - javascript

I'm building a "game" where a user clicks on an image and a number is randomly generated. With this number an image is assigned and displayed. Essentially a Rock, Paper, Scissors game. I'm just trying to get the random image to display. However I'm confused as how to go about setting the variable and then displaying it.
Originally I tried creating a variable that inside the switch would be something as follows
case 1:
cpuChoice = <img id="rock" src="rock.jpg" name="rock" width="265" height="250" />
break;
And then do a $("#result").html(cpuChoice); (result being a div id) However I had no luck with that. Further research seemed to suggest I have to store images in a cache, which is what my code currently is set up for. Though I don't believe I'm understanding how to utilize it properly.
The images I'm using are stored in a file with the pages.
Below is an example of my current javascript page.
$(document).ready(function(){
var cpuImage = new Image();
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
case 1:
document['rock'].src = rock.jpg;
break;
case 2:
document['paper'].src = paper.jpg;
break;
case 3:
document['scissors'].src = scissors.jpg;
break;
case 4:
document['spock'].src = spock.jpg;
break;
case 5:
document['rock'].src rock.jpg;
break;
}
document.['blank'].src =cpuImage.src;
});
blank is just the id of a temporary image I have. the code for it is as follows
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
I've done alert's to make sure my onclicks and the random number generator are both working, which they are. It appears that my problem is just getting the image that "the computer picks" to show.

Ok. A few issues are happening here, all of which are solvable. So...
$(document).ready(function(){
// You don't need an image object, since you're only
// determining a string for `src` and applying it to an existing
// image object
var cpuImage = "";
/* Below you're assigning `src` properties to objects that don't exist. */
rock.src = 'rock.jpg';
paper.src = 'paper.jpg';
scissors.src = 'scissors.jpg';
lizard.src = 'lizard.jpg';
spock.src = 'spock.jpg';
/* I see what you're trying to do,
but try going about it a bit differently, example: */
var imageBank = {
'rock' : 'rock.jpg',
'paper' : 'paper.jpg',
'scissors' : 'scissors.jpg',
'lizard' : 'lizard.jpg',
'spock' : 'spock.jpg'
};
$("#paper").click(function(){
var ranNumberOne = 1 + Math.floor(Math.random() * 5);
// the switch is for assigning the image based on what number is generated
switch(ranNumberOne){
// Assign your 'cpuImage' variable to the associated imageBank key
case 1:
cpuImage = imageBank['rock'];
break;
case 2:
cpuImage = imageBank['paper'];
break;
case 3:
cpuImage = imageBank['scissors'];
break;
case 4:
cpuImage = imageBank['lizard'];
break;
case 5:
cpuImage = imageBank['spock'];
break;
}
// Old:
document.['blank'].src =cpuImage.src;
// JQuery syntax (assuming you have an image with id `blank`)
// New:
$("#blank").attr('src',cpuImage);
});
Keep in mind, using things like a dictionary AKA an object as an associative array (which the imageBank variable is) helps to include a bunch more information pertaining to rock, scissors, etc. in one easy-to-maintain place. You can add additional info as well, which will save you time and code in the future.
Hope this helps and best of luck!

In honor of Sheldon Cooper, this FIDDLE might help.
JS
$('.clickme').on('click', function(){
var randimage = Math.floor(Math.random() * 5) + 1;
$('.putmehere').html('');
$('.random1').html(randimage);
$('.holder img#i' + randimage).clone().appendTo('.putmehere');
});

html
<div id="container">
<img id="blank" src="blank.jpg" name="blank" width="265" height="250" />
</div>
js
$(function () {
$("#container")
.attr("data-name", $("img", this).attr("id"))
.on("click", function (e) {
var options = ["rock", "paper", "scissors", "lizard", "spock", "blank"];
var r = (function (n) {
return options[(n + Math.floor(Math.random() * options.length - n))]
})(1);
$("img", this).attr({
"id": r,
"name": r,
"src": r + ".jpg"
}).parent().attr("data-name", r);
});
});
jsfiddle http://jsfiddle.net/guest271314/e3EXs/

Related

addEventListeter to an EventListener? (change the button)

I'm kinda new to js language, and I have this interesting project.
Have you ever played Poker?
So, when the user pressed the button, he sees three cards on the table. Then he presses the same 'check' button and he should see the fourth card, and then fifth.
How to change the button "job"? I mean. instead of making extra buttons for 4th and 5th card, can I make the game with only one?
Something like this can get you started:
var gamestate = "";
var update = function() {
switch (gamestate) {
case "":
$('#state').text("A(H) J(D) 10(S)") ;
gamestate = "flop";
break;
case "flop":
$('#state').text($('#state').text() + " 9(S)");
gamestate = "turn";
break;
case "turn":
$('#state').text($('#state').text() + " 4(H)");
gamestate = "river";
break;
case "river":
$('#state').text("");
gamestate = "";
break;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="state">
</div>
<a id='clickme' href="javascript:;" onclick="update()">Update</a>
where you have the ...text('info') blocks you would put your dealing cards code based on the game state.

Can't find image, but src is correct

I have a div at the bottom of the page that contains an image that changes based on a page variable. Here is my code to set the image:
<div>
<p>Data from #ViewBag.site.</p>
<div id="logo"></div>
</div>
<script>
var site = '#(ViewBag.site)';
var elem = document.createElement("img");
switch(site){
case "WeatherUnderground":
elem.src = '~/Images/wunderground.jpg';
break;
case "Forecast.io":
elem.src = '~/Images/fio.jpg';
break;
case "NOAA":
elem.src = '~/Images/noaa.png';
break;
case "WeatherUnlocked":
elem.src = '~/Images/wunlocked.jpg';
break;
case "APIXU":
elem.src = '~/Images/apixu.jpg';
break;
case "OpenWeatherMap":
elem.src = '~/Images/owm.jpg';
break;
}
elem.setAttribute("height", 100);
elem.setAttribute("width", 133);
elem.setAttribute("alt", site);
document.getElementById("logo").appendChild(elem);
</script>
When I visit this page, the image doesn't show up (instead, the alternate text plus black square/X combination shows up). When I inspect the alternate image, I see that it has the correct source. If I copy the source path into the browser, it does take me to the image, so I know the source is correct. However, the picture isn't showing up, so obviously something is wrong. Any thoughts?
You are doing a switch statement against a string that never changes.
var site = '#(ViewBag.site)';
But there is no case in your switch statement for this string so elem.src is never set.

localStorage, options data in selectmenu disappear when changing page

I have this code that writes entered phone numbers into defined options of a selectmenu, the problem is when i go back or quit the app the data are deleted and the list is empty. I can't find out why and how to fix this...
var flag_beneficiary_account_number=false;
var beneficiary_account_number;
if ( $('#beneficiary_number').val().length > 2 ) {
beneficiary_account_number=$('#beneficiary_number').val();
flag_beneficiary_account_number=true;
} else {
beneficiary_account_number = $('#Beneficiary_number_select').find(":selected").html();
flag_beneficiary_account_number=false;
}
if(flag_beneficiary_account_number){
if(localStorage.getItem("Beneficiary_number_select1")!=beneficiary_account_number &&
localStorage.getItem("Beneficiary_number_select2")!=beneficiary_account_number &&
localStorage.getItem("Beneficiary_number_select3")!=beneficiary_account_number){
var select_counter = parseInt(localStorage.getItem("select-counter"));
var select_option = select_counter%3;
select_counter = select_counter+1;
localStorage.setItem("select-counter",select_counter);
switch (select_option){
case 0:
localStorage.setItem("Beneficiary_number_select1",beneficiary_account_number);
$('#Beneficiary_number_select1').val(beneficiary_account_number);
$('#Beneficiary_number_select1').html(beneficiary_account_number);
break;
case 1:
localStorage.setItem("Beneficiary_number_select2",beneficiary_account_number);
$('#Beneficiary_number_select2').val(beneficiary_account_number);
$('#Beneficiary_number_select2').html(beneficiary_account_number);
break;
case 2:
localStorage.setItem("Beneficiary_number_select3",beneficiary_account_number);
$('#Beneficiary_number_select3').val(beneficiary_account_number);
$('#Beneficiary_number_select3').html(beneficiary_account_number);
break;
default:
break;
}
}
}
I was editing your question when you finally added the cordova tag. Things became clear so you need to remember that in cordova, to get the localStorage to work, use it this way
// To store
window.localStorage.setItem("Beneficiary_number_select2", beneficiary_account_number);
//and to access the value, use
window.localStorage.localStorage
.getItem("Beneficiary_number_select2");
instead localStorage.getItem("Beneficiary_number_select2")

Jssor refreshing .gif

I'm trying to load gif images into a jssor slider via code, but didn't work with my code and i don't know why.
The purpose is that each image refreshes when shown, cause the gif animation is not a loop, i have to do it this way.
Thanks in advance, here i put the code that is changing the images:
The variables wich will contain the images...
var imagen1 = new Image();
var imagen2 = new Image();
var imagen3 = new Image();
imagen1.src = "./1.gif";
imagen2.src = "./2.gif";
imagen3.src = "./3.gif";
And the code to change them...
function OnSlidePark(slideIndex, fromIndex) {
switch (slideIndex) {
case 0:
$('#i1').attr('src', imagen1.src);
break;
case 1:
$('#i2').attr('src', imagen2.src);
break;
case 2:
$('#i3').attr('src', imagen3.src);
break;
}
}
By the way, the sources and the Id's are working correctly
Will the following codes work?
function OnSlidePark(slideIndex, fromIndex) {
switch (slideIndex) {
case 0:
$('#i1').attr('src', '');
$('#i1').attr('src', imagen1.src);
break;
case 1:
$('#i2').attr('src', '');
$('#i2').attr('src', imagen2.src);
break;
case 2:
$('#i3').attr('src', '');
$('#i3').attr('src', imagen3.src);
break;
}
}

JavaScript function not respoding at first click

I have this on HTML:
<script type="text/javascript" src="./scripts/changeImage.js"></script>
<img id="myimage" onclick="changeImage()" src="./images/avatars/1.png"/>
This is the function
var cc=0;
function changeImage(){
if(cc==-1){
cc=0;
document.getElementById('myimage').src="./images/avatars/1.png";
} else if (cc==0){
cc=1;
document.getElementById('myimage').src="./images/avatars/2.png";
} else if (cc==1){
cc=2;
document.getElementById('myimage').src="./images/avatars/3.png";
} else if (cc==2){
cc=0;
document.getElementById('myimage').src="./images/avatars/4.png";
}
}
I must click 2 times to change the image. I tried some tricks but nothing.
i must click 2 times to change the image ...
At a guess, I'd say that cc starts out being -1, and so you follow this branch through your code:
cc=0;
document.getElementById('myimage').src="./images/avatars/1.png";
Since that's setting the same path that's already on the image, nothing changes. But then cc is 0, so the second click follows the next branch.
BTW, this is what switch statements are for:
function changeImage() {
switch (cc) {
case -1:
document.getElementById('myimage').src = "./images/avatars/1.png";
break;
case 0:
document.getElementById('myimage').src = "./images/avatars/2.png";
break;
case 1:
document.getElementById('myimage').src = "./images/avatars/3.png";
break;
case 2:
document.getElementById('myimage').src = "./images/avatars/4.png";
break;
}
cc = cc == 2 ? 0 : cc + 1;
}
Or a map:
var imageMap = {
-1: "./images/avatars/1.png",
0: "./images/avatars/2.png",
1: "./images/avatars/3.png",
2: "./images/avatars/4.png"
};
function changeImage() {
document.getElementById('myimage').src = imageMap[cc];
cc = cc == 2 ? 0 : cc + 1;
}
In both of the above, I've replicated the logic of your if/else series, but note that the logic of your if/else series never lets you get back to 1.png.
Also note that I'm assuming the real image paths are more complex, because otherwise you'd just want to key off the fact that you have 1.png, 2.png, etc.

Categories