Modifying a simple jquery game - javascript

I am trying to modify this game, right now it shows 9 images at random positions and the user has to click on them and when it reaches 10 clicks the game ends. I want to appear only one image. I will share the original function and the function I have modified it.
Original
function createImages(){
var myarray= ["img/img1.gif","img/img2.gif","img/img3.png",
"img/img4.gif","img/img5.gif","img/img6.gif",
"img/img7.gif","img/img8.png", "img/img9.jpg"];
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div"+i);
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = myarray[rand];
$('#div'+i).css("left", randPosition());
$('#div'+i).css("right", randPosition());
$('#div'+i).css("top", randPosition());
$('#div'+i).css("bottom",randPosition());
$('#div'+i).css("position","relative");
$('#div'+i).show();
div.appendChild(this.img);
$("body").prepend(div);
myarray.splice(rand,1);
count++;
}
}
After I modified it
function createImages(){
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div");
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = "img/img1.gif";
$('#div').css("left", randPosition());
$('#div').css("right", randPosition());
$('#div').css("top", randPosition());
$('#div').css("bottom",randPosition());
$('#div').css("position","relative");
$('#div').show();
div.appendChild(this.img);
$("body").prepend(div);
count++;
}
}
The problem is that now it appears the same image 10 times, I want it to appear only once and then disappear and appear again. Can anyone help me fix this issue.
If it's not to much to ask I would like to put this image inside a div so it wouldn't appear all over the page.
function randPosition() {
return 0 + Math.floor(Math.random() * 500);
}

In createImages() function you have a loop that adds the image 10 times:
for (var i = 0; i < 9; i++) {
...
}
Remove it, and it'll do it only once. Also you can simplify the code removing some random variables that are not used.
Further, this two sentences aren't correct. The first one creates a div in a variable named also div. The second is selector for all div elements, you are not referencing the new created one as I think you expect.
div = document.createElement("div");
$("div").attr("id","div");
You should create a jQuery object with the new created div to work with it:
var div = document.createElement("div");
$div = $(div); // << Create jQuery object wrapping the new div
$div.css("left", randPosition());
Edited function:
function createImages(){
var div = document.createElement("div");
$div = $(div);
$div.css("left", randPosition());
$div.css("right", randPosition());
$div.css("top", randPosition());
$div.css("bottom",randPosition());
$div.css("position","relative");
$div.show();
var img = document.createElement("img");
img.src = "http://dummyimage.com/25x25/4F4/000.png";
div.appendChild(img);
$("body").prepend(div);
}
EDIT: I've built a JSFiddle for you so you can play with it: http://jsfiddle.net/6aLh9qam/3/

Related

I have some JavaScript function that keeps repeating itself, I can't find why

This is code that generates a selected image when a function is run, but the image keeps changing, I want this code to let me have one image and keep it that way instead of it changing randomly every 0.5 - 3 seconds, and I don't know why!
const imageSelector = document.querySelector("#changeHeron")
function spinMachine() {
document.getElementById('spinner').disabled = 'disabled';
spinner.style.transform = "rotate(90deg)";
setInterval(enterBall, 1000)
var protmt = prompt("What's your name?")
alert("Hey there " + protmt + ", " + "its great to see you here")
}
function enterBall() {
var ball = document.getElementById("changeHeron");
ball.style.opacity = "100%";
ball.style.transform = "ScaleX(50%) ScaleY(50%)";
setInterval(liftBall, 1000);
}
function liftBall() {
var ball = document.getElementById("changeHeron");
ball.style.transform = "translateY(-250%)";
ball.style.transform = "ScaleX(200%) ScaleY(200%)";
ball.style.top = "40%";
setInterval(changeImage, 1500);
}
function changeImage() {
var images = ["./Images/Football.png", "./Images/Mousetache.png", "./Images/OG.svg"];
var randomNum = Math.floor(Math.random() * images.length);
var ball = document.getElementById("changeHeron");
ball.src = images[randomNum];
ball.style.borderRadius = "5%";
ball.style.backgroundColor = "white";
}
I found that you can place the images varible outside and change it inside when the code has ran so that the rest can just work outside of this problem

Increment not working in matching game

I am trying to call the same function with incremented numberOfFaces, but it loading with previous value of 5 only. What am I doing wrong? All I am trying to do is repeat the function after I click on the last child of the leftside.
var numberOfFaces = 5;
function generateFaces() {
var theRightSide = document.getElementById("rightSide");
var theLeftSide = document.getElementById("leftSide");
var theBody = document.getElementsByTagName("body")[0];
while(numberOfFaces > 0) {
// CREATING IMG ELEMENTS AND APPENDING THEM TO THE LEFTSIDE DIV
var img = document.createElement("img");
img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" ;
img.style.top = Math.floor(Math.random() * 400) +"px";
img.style.left = Math.floor(Math.random() * 400) +"px";
theLeftSide.appendChild(img);
// CLONING THE LEFT SIDE DIV ELEMENTS, REMOVING THE LAST CHILD AND APPENDING THEM TO THE RIGHT CHILD
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
numberOfFaces--;
}
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
while (theRightSide.firstChild) {
theRightSide.removeChild(theRightSide.firstChild);
}
numberOfFaces += 5;
generateFaces();
};
theBody.onclick = function gameOver(event) {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
}
Here:
numberOfFaces += 5;
generateFaces();
Your numberOfFaces value is 5 and you add 5 to it, so the result is 10. After that you call generateFaces, which will decrement numberOfFaces until it reaches 0, generating 10 faces and at next call will generate 5 faces according to the expectation. This happens inside theLeftSide.lastChild.onclick, so you expect your code to generate the faces and have numberOfFaces as 0 at the end when you click on that element. However, this click handler is defined inside generateFaces, which is never called, hence numberOfFaces is never changed. You need to refactor your code. Define your event handlers outside generateFaces and you should be ok after that.

Randomize background img with JS

I have working code, that randomly changes background of the body with my gif's.
var totalCount = 11;
function ChangeIt() {
var num = Math.ceil( Math.random() * totalCount );
document.body.background = '/static/img/'+num+'.gif';
document.body.style.backgroundRepeat = "repeat";
}
window.onload = ChangeIt;
Now I want to use it with another HTML element, one of the div's, for example. Changing document.body.background to document.getElementById('id').background doesn't work. How should I change the code?
document.body.background mostly worked for body background but not other html elements.So used this document.getElementById('id').style.backgroundImage = "url(..)";
var totalCount = 11;
function ChangeIt() {
var divs =document.getElementById('id');
var num = Math.ceil( Math.random() * totalCount );
divs.style.backgroundImage = 'url(/static/img/'+num+'.gif)';
divs.style.backgroundRepeat = "repeat";
divs.style.height = "300px"; //testing
}
window.onload = ChangeIt;
Have you tried this?
document.getElementById('id').style.backgroundImage = "url('/static/img/" + num + ".gif')";
Also, the RNG with Math.ceil() means that images are based on 1 not on 0:
1.gif
2.gif
...
11.gif
If this is not the case use Math.floor():
0.gif
1.gif
...
10.gif
Depending on what the element is, you may need to set its dimensions (width and height). This is an example HTML element:
<div id="imagediv" style="width: 320px; height: 640px; background-repeat: repeat;"></div>
This the resulting code:
var totalCount = 11;
window.onload = function () {
var num, node;
num = Math.ceil(Math.random() * totalCount);
node = document.getElementById("imagediv");
node.style.backgroundImage = "url('/static/img/" + num + ".gif')";
};
this should be the correct syntax:
document.getElementById('id').style.backgroundImage = "url('img_tree.png')";

Change random result to sequence

How to change this random result into a sequence starting from lower number? I am new in JS and have tried to make modification with no solution. I hope anybody can help.
function randomFeed() {
var $el = $("#randomFeed");
var random = new Array('news1','news2','news3','news4','news5','news6');
var randomIndex = Math.floor(Math.random() * 4);
var newElement = random[randomIndex];
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
So you need sequential news slide instead of random? Try this (note the global feedIndex variable)
var feedIndex = 0;
function randomFeed() {
var $el = $("#randomFeed"),
news = new Array('news1','news2','news3','news4','news5','news6'),
newElement = news[feedIndex++ % news.length];
//console.log(newElement);
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
BTW, this code in it's state is very bad. It changes the DOM every time to show new feed element. It is better to render all elements whith display:none and only toggle visibility of actual one. It is common pattern
Try this:
news = new Array('news1','news2','news3','news4','news5','news6')
// option 1
news.sort(function() {
return .5 - Math.random();
});
//news = news1,news2,news3,news6,news4,news5
//option 2
len = news.length,
randomNumber = Math.floor((Math.random() * len) + 0);
// randomNumber = 3
part = news.slice(randomNumber, len)
// part = arrnews6,news4,news5
Please be more precise what are you expecting/about what your goal is!

Why is it looping through the 'else' in my if/else statement?

If you enable the alert(rand) at the bottom of my if/else statement, you will notice that when ran, it will constantly loop over the else section of my if/else statement. It's probably a simple fix, but I can't seem to figure it out. I had it working in the earlier stages of development but can't seem to figure it out now.
I'll post the code below, but it's probably easier to look at my jsfiddle, here: http://jsfiddle.net/zAPsY/7/ Thanks.
$(document).ready(function(){
//You can edit the following file paths to change images in selection
var img1 = '<img src="images/luke.jpg">';
var img2 = '<img src="images/luke.jpg">';
var img3 = '<img src="images/luke.jpg">';
var img4 = '<img src="images/luke.jpg">';
var img5 = '<img src="images/luke.jpg">';
var img6 = '<img src="images/luke.jpg">';
var all = img1 + img2 + img3 + img4 + img5 + img6;
//Rotation
var speed = 0.00;
var radius = 80;
var count = 0;
$("#run").bind("click",runButtonClick);
function rotate()
{
var centerx = $(document).width()/2;
var centery = $(document).height()/2;
var num_items = $("#container > img").length;
$("#container > img").each(function(){
var angle = count * (Math.PI/180);
var newx = centerx + Math.cos(angle)*radius - $(this).width()/2;
var newy = centery + Math.sin(angle)*radius - $(this).height()/2;
$(this).css("left",newx+"px").css("top",newy+"px");
count += 360/num_items + speed;
});
}
setInterval(rotate,100/1000);
//Append elements to container
$("#appendall").click(function(){$('#container').append(all);});
$('#append').children().eq(2).click(function(){$('#container').append(img1);});
$('#append').children().eq(3).click(function(){$('#container').append(img2);});
$('#append').children().eq(4).click(function(){$('#container').append(img3);});
$('#append').children().eq(5).click(function(){$('#container').append(img4);});
$('#append').children().eq(6).click(function(){$('#container').append(img5);});
$('#append').children().eq(7).click(function(){$('#container').append(img6);});
//Refresh page
$("#reset").click(function(){location.reload();});
//IF speed is greater than 0 - ELSE add animation to div element
function runButtonClick() {
var maxcount = 0.40;
var incdec = 0.01;
setInterval(function(){counter();}, 100);
counter()
speed;
function counter()
{
if (maxcount >= 0.00)
{
maxcount = maxcount - incdec;
speed = speed + incdec;
//alert(speed)
//alert(maxcount)
}
else if (maxcount <= 0.00)
{
speed = 0.00;
//Find amount of div elements and add 1
var brewees = $('#container').children().length +=1;
//get a random number
var rand = (Math.floor(Math.random()*brewees));
var ap = '20px';
var ab = '#ddd';
var ad = 1000;
//match random number corrosponding child in div
$('#container').children().eq(parseFloat(rand))
.animate({padding: ap, background : ab}, {duration:ad});
alert(rand);
}
}
}
});
You let your maxcount drop below zero but still your function is being called every 100ms (due to your setInterval).
So you should clear that interval eventually by doing:
/* first */
var intervalID = setInterval(function(){counter();}, 100);
/* later */
clearInterval(intervalID);
You're calling the function at a rate of 10 times per second (setInterval). Eventually, the maxcount variable will drop below 0, causing the else condition to execute.
You should store the interval call in a variable, and use clearInterval at else, so that the function runs only once after else:
//Store a reference to the interval
var interval = setInterval(function(){counter();}, 100);
...
function counter(){
...
else if(..){
...
clearInterval(interval); //Clear the previously defined interval
}
...
Another note: In the code, speed; has no use. Either prefix it by var (var speed;), or remove it.

Categories

Resources