jQuery CrystalsCollector Game - javascript

I created a Crystal Collector game where you have to click a crystal and get to a random number based on each crystal having a hidden value. In my click functions I can have 4 different click functions for each crystal but would like to consolidate 4 actions into one function. Here are the two snippets of code for the HTML and javascript pages we need to complete this:
HTML......
<div class="buttons">
<img class="image" id="image1" src="assets/images/crystal1.png">
<img class="image" id="image2" src="assets/images/crystal2.png">
<img class="image" id="image3" src="assets/images/crystal3.png">
<img class="image" id="image4" src="assets/images/crystal4.png">
</div>
javaScript.....
$(document).ready(function() {
var random = Math.floor(Math.random()*102+19);
$("#numberToGet").text(random);
var num1 = Math.floor(Math.random()*12+1);
var num2 = Math.floor(Math.random()*12+1);
var num3 = Math.floor(Math.random()*12+1);
var num4 = Math.floor(Math.random()*12+1);
var userTotal= 0;
var wins = 0;
var losses = 0;
$("#numberWins").text(wins);
$("#numberLosses").text(losses);
function reset() {
random = Math.floor(Math.random()*102+19);
console.log(random);
$("#numberToGet").text(random);
var num1 = Math.floor(Math.random()*12+1);
var num2 = Math.floor(Math.random()*12+1);
var num3 = Math.floor(Math.random()*12+1);
var num4 = Math.floor(Math.random()*12+1);
userTotal = 0;
$("#score").text(userTotal);
}
function winner() {
alert("You Won!!");
wins++;
$("#numberWins").text(wins);
reset();
}
function loser() {
alert("You Lose!!");
losses++;
$("#numberLosses").text(losses);
reset();
}
$("#image1").on("click", function() {
userTotal = userTotal + num1;
console.log("New userTotal " + userTotal);
$("#score").text(userTotal);
if (userTotal === random) {
winner()
}
else if (userTotal > random) {
loser()
}
})
});
For the bottom "image1" click function, I want to apply this to all 4 crystals each still having a different hidden value. I included a class "image" for each picture and thought if I called the click function for the class "image" and then somehow created a value attribute for the random number each crystal is worth in there somewhere that this would achieve what I want. Any advice to push me in the right direction would help greatly!

There are many ways, but you could do something like...
//....
var crystalValues = {};
crystalValues[1] = Math.floor(Math.random()*12+1);
crystalValues[2] = Math.floor(Math.random()*12+1);
crystalValues[3] = Math.floor(Math.random()*12+1);
crystalValues[4] = Math.floor(Math.random()*12+1);
//.... more code here
function getCrystalHandler(crystalKey) {
return function() {
userTotal = userTotal + crystalValues[crystalKey];
console.log("New userTotal " + userTotal);
$("#score").text(userTotal);
if (userTotal === random) {
winner()
}
else if (userTotal > random) {
loser()
}
}
}
$("#image1").on("click", getCrystalHandler(1));
$("#image2").on("click", getCrystalHandler(2));
$("#image3").on("click", getCrystalHandler(3));
$("#image4").on("click", getCrystalHandler(4));

Not sure if this is what you are going for but if you are creating the crystals in html then go ahead and assign them all a class. So that way they are all apart of class="crystals". Next you want to give them an onclick handler. So to catch you up it should look like this.
<img class="crystals" onclick="popCrystal(event, 'image1')" id="image1" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image2')" id="image2" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image3')" id="image3" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image4')" id="image4" src="assets/images/crystal1.png">
and then we will make a function called popCrystal to be called when someone clicks a crystal.
function popCrystal(evt, getCrystal) {
document.getElementById(getCrystal).style.float = "right";
}
If you have any questions just tag me in the post.
edit: I just realized this is hard to read... Im sorry about that. I am at work so I am not going to rewrite it but I will explain a little bit.
This is how onclick works:
onclick is an event listener that gets triggered with the DOM element is clicked. It calls a function which we called "popCrystal". popCrystal has to arguments which are event, and the id of the current div. So you see how we go from image1 to image4 along side the respective id's? That's so we can call the specific element later on.
finally we get to the javascript. This is where we actually make the "popCrystal" function. We will populate it with the same to arguments as the one in the div elements. Inside the function is where you will put your code telling it what to do. I simply used float right to show you how it selects the individual elements.
Hope that helps even though my explanation is quite sloppy.

Related

Random image function (javaScript) not displaying local image when prompted

So I've tried several things to fix this but nothing seems to work. it was working OKAY earlier but something happened and now I cant get it to display a random image from a JS array in the target div.
renamed all the image files so they had no spaces
edited document.getElementById("profPic").innerHTML = '<img src="'+imagesArray[num]+'">'; several times to no avail
Checked SO for solutions/work around but concluded it must be something to do with the file formatting that i am unaware of.
Tried putting displayImage(); in the div container. Also tried with document.write
var imagesArray = ["img/mascotImages/CCF2_(281).jpg", "img/mascotImages/CCF2_(282).jpg"];
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length + 1));
document.getElementById("profPic").innerHTML = '<img src="' + imagesArray[num] + '">';
}
function myFunction(e) {
if ((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton') {
e.preventDefault();
var searchValue = document.getElementById("mySearch").value;
for (var i = 0; i < users.length; i++) {
if (users[i]['last_name'] === searchValue) {
document.getElementById("usernameOut").innerHTML = (users[i].username);
document.getElementById("firstNameOut").innerHTML = (users[i].first_name);
displayImage();
return;
}
}
}
}
<div id="return">
<div id="profPic"></div>
<!--profPic-->
<div id="usernameOut"></div>
<!--usernameOut-->
<div id="firstNameOut"></div>
<!--firstNameOut-->
</div>
What is supposed to happen is that when the user searches something in a search box, data from another array is displayed in <div id="usernameOut"> and <div id="firstNameOut"> etc. I wanted a random picture to display also when the user clicked search/hit enter.
Is something wrong with the naming conventions of the files? are they in one too many folders? i'm sure this is something very simple, but it's had me staring at it for several hours.
Arrays indexes start with 0, not 1. Therefore, with only 2 images in your array, the max index should be 1. But your code Math.floor(Math.random() * (imagesArray.length+1)) can at times return 2.
Just get rid of the +1:
Math.floor(Math.random() * imagesArray.length)

javascript/html: Second onclick attribute

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}

Random image click

So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.
function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}
Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?
You can try to select the image who have the wanted source.
And add a class or id to your paragraph for readability.
document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};
Example
document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
document.getElementById("rep").innerHTML="you win !";
}
img{
height:100px;
width:100px;
}
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">
<script type="text/javascript" >
var images = document.getElementsByTagName('img');
//find all paragraphs
var paragraphs = document.getElementsByTagName('p');
//define function called on click
function changeParagraph() {
//change first paragraph if exists
if(paragraphs.length) {
paragraphs[0].innerHTML = 'I have been changed!';
}
}
/*
for(var i = 0; i < images.length; i++) {
//set onclick event to every image
images[i].onclick = changeParagraph;
}
*/
// set onclick to the randomImage
images[randomNumber].onclick = changeParagraph;
</script>
Assuming your first paragraph exists before the user clicks the picture, you can add an onClick element to your img tag. Try something like this, changing the URL obviously for your own picture:
<p id = "first">You haven't found Waldo
</p>
<img id = "waldo" src = https://pbs.twimg.com/profile_images/561277979855056896/4yRcS2Zo.png
onclick = "addparagraph()"
/>
JavaScript:
function addparagraph(){
document.getElementById("first").innerHTML = "you found Waldo!";
}

How to make an image change into others on click?

I'm trying to make a sort of a minimal clickable "slideshow". So far I have only managed to make the image change into another. but I want to add other images to it. I tried to add other ifs and elses on the javascript but it doesn't work. (I'm a noob...) How can I do it? I juts want to click and the images change. This is my code so far:
<div> <img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage()"/> </div>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "1.jpg")
{
document.getElementById("imgClickAndChange").src = "2.jpg";
document.getElementById("imgClickAndChange").src = "3.jpg";
}
}
</script>
thank you!
In your condition you need a double equals == - you can also pass this in to avoid getElementById multiple times. If you want to make a cycler - you can put your sources into an array and cycle thru that:
<img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage(this)"/>
var images = ["1.jpg", "2.jpg", "3.jpg"];
function changeImage(img) {
var currentIndex = images.indexOf(img.src);
var zeroBasedLength = images.length - 1;
if (currentIndex == zeroBasedLength)
img.src = images[0];
else
img.src = images[++currentIndex];
}
If you want to cycle through those images, I'd make an array and swap the position of the elements in it like:
var imgs = ["2.jpg", "3.jpg", "1.jpg"];
function changeImage() {
document.getElementById("imgClickAndChange").src = imgs[0];
imgs.push(imgs.shift())
}
jsFiddle example

Switching image with Next/Previous buttons

Is there any way to switch images using next/prev buttons with jQuery? Here's the code:
<div class="prevDiv">
<img src="images/prev.png" alt="previous" />
</div>
<div class="pic" id="picwebd">
<img src="images/portfolio/webdesign/webd1.jpg" class="portPic" />
</div>
<div class="nextDiv">
<img src="images/next.png" alt="previous" />
</div>
I tried modifying this code to my needs: http://jsfiddle.net/x5mCR/16/ but I haven't succeed. I think that incrementing and decrementing number in the image src would be enough, but I can't come up with decent code do this. Google doesn't help neither.
In case anyone reading this post want a different approach still using JQuery fadeIn, Im posting below the code for that.
Here you can find the fiddle for it.
Here's the Javascript Part
//At the start will show the first image
$('#fullimage img.fullimage:first-child').fadeIn();
//Keep track of the image currently being visualized
var curr = $('#fullimage img.fullimage:first-child');
$('#next').on('click', function() {
//Hide Current Image
curr.hide();
//Find Next Image
var next = curr.next();
//If theres no next image (is the last img), go back to first
if (next.length == 0) next = $('#fullimage img:first');
//Fade In
next.fadeIn();
//Save in curr the current Image
curr = next;
return false;
});
$('#prev').on('click', function() {
curr.hide();
var prev = curr.prev();
if (prev.length == 0) prev = $('#fullimage img:last');
prev.fadeIn();
curr = prev;
return false;
});
Here's the HTML part
<div id="fullimage">
<img class="fullimage" src="http://i.imgur.com/RHhXG.jpg" />
<img class="fullimage" src="http://i.imgur.com/p1L2e.jpg" />
<img class="fullimage" src="http://i.imgur.com/NsrI0.jpg" />
<img class="fullimage" src="http://i.imgur.com/Ww6EU.jpg" />
</div>
<label id="prev">previous</label>
<label id="next">next</label>
Here is dynamic and simple script reducing your html code
http://jsfiddle.net/x5mCR/32/
$("#thumbnail a").on('click', function (eve) {
eve.preventDefault();
var link = ($(this).attr("href"));
var content = '<img src="' + link + '"/>';
$("#fullimage").hide().html(content).fadeIn('slow');
});
Remove the anchors with class thumbnail and give the corresponding <img> tags the thumbnail class, then use jQuery click methods for the thumbnail class:
$(".thumbnail").click(function() {
$(".fullimage").src = $(this).attr("src");
});
Make sure you have a single .fullimage in the #fullimage div.
This isn't the same as a next / previous button - but it would fix the JSFiddle that you made.
http://jsfiddle.net/x5mCR/34/
var picNumber = 1;
$(".nextDiv").click(function() {
picNumber++;
if (picNumber > 3) picNumber = 1; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
$(".prevDiv").click(function() {
picNumber--;
if (picNumber < 1) picNumber = 3; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
If I understand correctly, you're trying to use the arrow keys to move back and forth between pictures...so if this is the case, I would recommend taking a look at this post: Binding arrow keys in JS/jQuery
Also, for your convenience, I just took the code from that post and combined it with the function in your fiddle to get this:
$(document).keydown(function (e) {
if (e.keyCode == 39) {
$(".fullimage").hide();
var next = $(this).next();
if (next.length > 0) {
next.fadeIn();
} else {
$('#fullimage img:first').fadeIn();
}
return false;
}
});
In testing it looks like it might need some modification, and also, you would obviously need to create a similar function for when the back button is pressed, but I think if I'm understanding your issue correctly this is a good starting place.

Categories