using jQuery to append div's and each div has a different ID - javascript

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>

Use an unique class with all of then, and call then by class

Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Related

JavaScript doesn't display as intended on HTML Site

I am building an example in a book trying to learn JavaScript but for some reason it doesn't look like it reading the JS file when I run the html. What am I missing? The HTML and CSS shows up just fine, but when I try to enter new values its doesn't do anything. Its seems like its not reading the JS file. They are all in the same directory as well when ran.
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var n = 4;
var size = 10;
var $ = function(id) {
return document.getElementById(id);
};
function addScore() {
var name = $('name').value;
var score = $('score').value;
if (name == "" || score == "" || isNaN(score)) alert("Invalid data ");
else if (n < size) {
names[n] = name;
scores[n] = score;
n++;
} else alert("Array already full");
}
function displayResults() {
var h, avg, name;
h = scores[0];
name = names[0];
avg = 0;
for (z = 0; z < n; z++) {
if (h > scores[0]) {
h = scores[z];
name = names[z]
}
avg = avg + scores[z];
}
avg = avg / n;
var con = "<B>Results </b><br> Average Score= " + avg + "<br>Highest Score = " + name + " with a score of " + h;
$('results').innerHTML = con;
}
function displayScores() {
var con = "<tr><td colspan='2'><h2>Scores</h2></td></tr><tr><td>Name</td><td>Score</td></tr> ";
for (z = 0; z < n; z++) {
con = con + "<tr><td>" + names[z] + "</td><td>" + scores[z] + "</td></tr>"
}
$('scores_table').innerHTML = con;
}
window.onload = function() {
$("add").onclick = addScore;
$("display_results").onclick = displayResults;
$("display_scores").onclick = displayScores;
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
padding: 10px 20px;
width: 600px;
border: 3px solid blue;
}
h1 {
color: blue;
margin-top: 0;
margin-bottom: .5em;
}
h2 {
color: blue;
font-size: 120%;
padding: 0;
margin-bottom: .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 3em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
p {
margin: 0;
}
td {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="test_scores.js"></script>
</head>
<body>
<main>
<h1>Use a Test Score array</h1>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_results" value="Display Results">
<input type="button" id="display_scores" value="Display Scores"><br>
<div id="results"></div>
<table id="scores_table"></table>
</main>
</body>
</html>
Expected Outcome:
EDIT:
Upon closer inspection and learning about the exception message you're getting, you seem to be using jQuery and those jQuery selectors don't seem to be targeting valid html elements.
You need to make sure you're including the jQuery library (which you appear not to be doing) and that you're using the right syntax in your jQuery selectors, such as using $('#add') instead of $('add') and that elements have the corresponding Id associated to them. You have several problems like this in your code.
If you really want to use jQuery just add the '#' symbol before the name of each jQuery selector. I've modified the code. Upload the updated JS to your js file (without the start and close tag) and try again.
I suggest you don't use jQuery just now and replace the jQuery selector for vanilla JS (pure JS). For that, instead replace every instance of $('...') with document.getElementById('...'), where ... is the name of your element's ID attribute.
Original answer:
With the provided information it's not possible to determine what the issue is. But you could try different things to find out.
If you're using Google Chrome browser. Google dev tools is a mandatory tool to troubleshoot, test and track your code in-browser. You can find an intro to Google Chrome Dev Tools here.
I suspect that your JS file is either not called test_scores.js or is not in the same location as your HTML file.
To test this, I suggest you try loading your JS directly in your HTML file. To achieve that just replace the line in your HTML file:
<script src="test_scores.js"></script>
with the following:
<script>
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var n = 4;
var size = 10;
var $ = function(id) {
return document.getElementById(id);
};
function addScore() {
var name = $('#name').value;
var score = $('#score').value;
if (name == "" || score == "" || isNaN(score)) alert("Invalid data ");
else if (n < size) {
names[n] = name;
scores[n] = score;
n++;
} else alert("Array already full");
}
function displayResults() {
var h, avg, name;
h = scores[0];
name = names[0];
avg = 0;
for (z = 0; z < n; z++) {
if (h > scores[0]) {
h = scores[z];
name = names[z]
}
avg = avg + scores[z];
}
avg = avg / n;
var con = "<B>Results </b><br> Average Score= " + avg + "<br>Highest Score = " + name + " with a score of " + h;
$('#results').innerHTML = con;
}
function displayScores() {
var con = "<tr><td colspan='2'><h2>Scores</h2></td></tr><tr><td>Name</td><td>Score</td></tr> ";
for (z = 0; z < n; z++) {
con = con + "<tr><td>" + names[z] + "</td><td>" + scores[z] + "</td></tr>"
}
$('#scores_table').innerHTML = con;
}
window.onload = function() {
$("#add").onclick = addScore;
$("#display_results").onclick = displayResults;
$("#display_scores").onclick = displayScores;
};
</script>
If this doesn't solve it. Another issue could be that you're getting a cached version of your application. Try hard reloading your page (clear cache and reload) and see if that makes a difference.

How should I refer back to the an element before (in a different function), and modify it in a new function?

How do I make reference to the specific dashes I created, and add a
specific letter to them. Read the comments and code to get a better
context. Thanks for any help in advance!!
<!Doctype html>
<html lang="en">
<head>
<style>
ul {
display: inline;
list-style-type: none;
}
.boxes {
font-size:1.6em;
text-align:center;
width: 10px;
border-bottom: 3px solid black;
margin: 5px;
padding: 10px;
display: inline;
}
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}
</style>
</head>
<body>
<script>
var possibleWord = ["COW", "BETTER", "HARDER", "JUSTIFY", "CONDEMN",
"CONTROL", "HELLO", "UNDERSTAND", "LIFE", "INSIGHT","DATE",
"RIGHTEOUSNESS"];
var hangmanWord = possibleWord[Math.floor(Math.random() *
possibleWord.length)];
var underlineHelp;
var space;
var guess;
var guesses = [];
var placement;
var underscores = [];
var character = [];
var textNodes = [];
window.onload = function () {
placement = document.getElementById('hold');
underlineHelp = document.createElement('ul');
placement.appendChild(underlineHelp);
for (i = 0; i < hangmanWord.length; i++) {
underscores = document.createElement('li');
underscores.setAttribute('class', 'boxes');
guesses.push(underscores);
underlineHelp.appendChild(underscores);
character = document.createElement('span');
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('hidden');
underscores.appendChild(character);
}
This is the area I want to refer to later.
for(x=1;x<=26;x++){
document.getElementById("test").innerHTML = hangmanWord;
var btn = document.createElement("BUTTON");
var myP = document.createElement("br");
var letter = String.fromCharCode(x+64);
var t = document.createTextNode(letter);
btn.appendChild(t);
btn.id = letter;
Just creating buttons. This is important when I say 'this.id' down below.
btn.addEventListener("click", checkLetter);
document.body.appendChild(btn);
//add a line break 'myP' after 3 buttons
if (x%10==0) {
document.body.appendChild(myP);
}
}
}
function checkLetter(){
//this refers to the object that called this function
document.getElementById("p1").innerHTML += this.id;
for (i = 0; i < hangmanWord.length; i++) {
guess = hangmanWord[i];
if (this.id == guess) {
character[i] = hangmanWord[i];
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('visible');
}
}
}
Here is where I am in trouble. If I do this (the code I wrote after the if statement) the letters will be added on the end of the string. I Want to have it on the specific dashes that I created earlier. How can I manage to do that? Do I have to do something called "object passing." I am relatively new to js (high school student) and I am keen on any insight! Once again thanks for the help in advance!
</script>
</head>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<div id = "contents">
<div id = "hold"></div>
</div>
<p id ="p1"> Letters picked: </p>
<div id= "picBox"></div>
<div id = "test"></div>
</div>
</body>
You could store the guessing word and the guessed characters in an object and just output the replaced result of such instead. Seems easier to me.
<html>
<head>
<script>
//The hangman object
var Hangman = {
wordToGuess: 'RIGHTEOUSNESS', //The word to guess. Just one for my example
guessedLetters: [] //The guessed characters
};
window.onload = function(){
//Creating the buttons
for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
var tLetter = String.fromCharCode(x+64),
tButton = tF.appendChild(document.createElement("button"));
tButton.id = tLetter;
tButton.addEventListener("click", checkLetter);
tButton.appendChild(document.createTextNode(tLetter));
(x%10 === 0) && tF.appendChild(document.createElement('br'))
};
document.body.appendChild(tF);
startTheGame()
};
//Starts a game of hangman
function startTheGame(){
var tWord = Hangman.wordToGuess,
tPlacement = document.getElementById('hold');
document.getElementById('test').innerHTML = tWord;
//Resetting the guesses
Hangman.guessedLetters = [];
//Creating dashes for all letters in our word
for(var i=0, j=tWord.length; i<j; i++){
tPlacement.appendChild(document.createTextNode('_'))
}
}
function checkLetter(){
var tButton = this,
tLetter = tButton.id,
tWord = Hangman.wordToGuess,
tPlacement = document.getElementById('hold');
//Make a guess
document.getElementById('p1').innerHTML += tLetter;
(Hangman.guessedLetters.indexOf(tLetter) === -1) && Hangman.guessedLetters.push(tLetter.toLowerCase());
//Clear the current word
while(tPlacement.firstChild) tPlacement.removeChild(tPlacement.firstChild);
//Now we reverse replace the hangman word by the guessed characters
for(var i=0, j=tWord.length; i<j; i++){
tPlacement.appendChild(document.createTextNode(
(Hangman.guessedLetters.indexOf(tWord[i].toLowerCase()) === -1) ? '_' : tWord[i]
))
}
}
</script>
</head>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<div id = 'contents'>
<div id = 'hold'></div>
</div>
<p id = 'p1'> Letters picked: </p>
<div id= "picBox"></div>
<div id = "test"></div>
<!-- This one seems to be too much
</div>
-->
</body>
</html>
https://jsfiddle.net/zk0uhetz/
Update
Made a version with propert object handling, separating the actual hangman logic from the interface.
<html>
<head>
<style>
button{
margin: 1px;
min-width: 30px
}
button[disabled]{
background: #777;
color: #fff
}
</style>
<script>
//Handles the hangman game itself
;(function(ns){
'use strict';
var _listOfWord = ['COW', 'BETTER', 'HARDER', 'JUSTIFY', 'CONDEMN', 'CONTROL', 'HELLO', 'UNDERSTAND', 'LIFE', 'INSIGHT','DATE', 'RIGHTEOUSNESS'],
_wordToGuess = null, //The word to guess. Just one for my example
_guessedLetters = [] //The guessed characters
ns.Hangman = {
//Returns the current obstructed word
getCurrentObstructedWord: function(){
var tWord = []; //The current state of the game
if(_wordToGuess){
//Now we reverse replace the hangman word by the guessed characters
for(var i=0, j=_wordToGuess.length; i<j; i++){
tWord.push(
(_guessedLetters.indexOf(_wordToGuess[i].toLowerCase()) === -1) ? '_' : _wordToGuess[i]
)
}
};
return tWord
},
//Make a guess at the current game
Guess: function(letter){
//Add the guess to the list of guesses, unless already guessed
(_guessedLetters.indexOf(letter) === -1) && _guessedLetters.push(letter.toLowerCase());
return this.getCurrentObstructedWord()
},
isComplete: function(){
return !!(this.getCurrentObstructedWord().indexOf('_') === -1)
},
//Starts a new game
Start: function(){
_guessedLetters = []; //Resetting the guesses
_wordToGuess = _listOfWord[Math.floor(Math.random() * _listOfWord.length)];
return _wordToGuess
}
}
}(window._ = window._ || {}));
//Creates the buttons for hangman
function createButtons(){
var tContainer = document.querySelector('#buttons');
while(tContainer.firstChild) tContainer.removeChild(tContainer.firstChild);
//Creating the buttons
for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
var tLetter = String.fromCharCode(x+64),
tButton = tF.appendChild(document.createElement('button'));
tButton.id = tLetter;
tButton.addEventListener('click', makeAGuess);
tButton.appendChild(document.createTextNode(tLetter));
(x%10 === 0) && tF.appendChild(document.createElement('br'))
};
tContainer.appendChild(tF)
};
//Makes a guess
function makeAGuess(){
var tButton = this,
tLetter = tButton.id;
//Disable the button
tButton.setAttribute('disabled', 'disabled');
//Make a guess
var tElement = document.getElementById('hold');
tElement.textContent = _.Hangman.Guess(tLetter).join('');
//Check if finished
if(_.Hangman.isComplete()){
tElement.style.color = 'limegreen'
}
};
//Starts a new game of hangman
function Reset(){
createButtons(); //Recreated the buttons
_.Hangman.Start(); //Starting a game of hangman
var tElement = document.getElementById('hold');
tElement.textContent = _.Hangman.getCurrentObstructedWord().join('');
tElement.style.color = ''
};
window.onload = function(){
Reset()
};
</script>
</head>
<body>
<div id = 'hold'></div>
<p id = 'p1'>Make a guess:</p>
<div id = 'buttons'></div>
<br /><br />
<button onclick = 'Reset()'>Start a new game</button>
</body>
</html>
https://jsfiddle.net/mm6pLfze/

two dimensional array random generator jQuery

All rows always have same numbers, why? They should take random number to populate it. Also, how can I repair it? Once I saw answer here but now I cannot find it.
var mapSizex = 5;
var mapSizey = 6;
var mapArray = [];
$(function() {
console.log("ready!");
$('#map-draw').html(drawMap());
});
function mapGenerator() {
for (i = 0; i < mapSizex; i++) {
for (x = 0; x < mapSizey; x++) {
mapArray[i, x] = getRandom(1, 5);
}
}
}
function drawMap() {
mapGenerator();
var map = '';
tileID = 0;
for (i = 0; i < mapSizex; i++) {
map = map + '<br style="clear: both;">';
for (x = 0; x < mapSizey; x++) {
map = map + '<div class="tile tileID' + tileID + '">' + mapArray[i, x] + '</div>';
tileID++;
}
}
return map;
}
function getRandom(min, max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}
.tile {
float: left;
height: 20px;
width: 20px;
border: 1px solid black;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="map-container">
<div id="map-draw"></div>
</div>
</div>
To post it I need to add some more content but all included information's should be enough to find what I mean.
here is a link to JSFIDDLE woking code
It should be mapArray[i][x] and I added mapArray[i]=[]; in the outer loop.
here is your fixed code:
var mapSizex=5;
var mapSizey=6;
var mapArray=[];
$(function() {
console.log( "ready!" );
$('#map-draw').html(drawMap());
});
function mapGenerator(){
for(i=0;i<mapSizex;i++){
mapArray[i]=[];
for(x=0;x<mapSizey;x++){
mapArray[i][x]= getRandom(1,5);
console.log(i,x,getRandom(1,5))
}
}
}
function drawMap(){
mapGenerator();
console.log(mapArray)
var map='';
tileID=0;
for(i=0;i<mapSizex;i++){
map=map+'<br style="clear: both;">';
for(x=0;x<mapSizey;x++){
map=map+'<div class="tile tileID'+tileID+'">'+mapArray[i][x]+'</div>';
tileID++;
}
}return map;
}
function getRandom(min,max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}

Javascript end game when click on image

Hey this is my first time on Stackoverflow!
I am building a small javascript html5 game where you click on objects kind of like whack-a-mole.. The goal is to kill as many "gem green" and " gem blue" as possible in 10 seconds, and when you click on the "gem red".. the game ends and plays a sound.
I got most things to work, except I can't find a way to make the game end when clicking on "gem red".. I have tried lots of functions and listeners.. but to no avail.. can anyone help me figure this out?
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
position: relative;
color: #ffffff;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
var interval = setInterval(Spawn, 750);
var count = 10;
var counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
Stop(interval);
Stop(counter);
time.innerHTML = "Game Over!";
start.style.display = "block";
UpdateScore();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
Alessio -
You only need a few minor changes to your code to make it work. The example below should help you get started in the right direction. Good luck.
Changes:
Add an endGame() function and move the stop game logic from the timer() function into it.
Add a line to the click() function to check for red gem clicks.
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
Declare the count, counter, and interval variables at the top of your Game object.
The code below also has a few minor CSS changes used for debugging which you can remove.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
border: 1px red dotted;
position: relative;
color: red;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
background-color: green;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
background-color: blue;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
background-color: red;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
var interval, counter, count;
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
function endGame( msg ) {
count = 0;
Stop(interval);
Stop(counter);
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
time.innerHTML = msg || "Game Over!";
start.style.display = "block";
UpdateScore();
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
interval = setInterval(Spawn, 750);
count = 10;
counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
endGame();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
For starters, you shouldn't include a style sheet and your entire HTML file since neither is relevant and you should use a canvas element instead of this chaotic use of CSS and html elements, which would allow the size of your code to be halved. Furthermore, you should be able to fix this by just changing some global boolean variable to false when the red gem is clicked and when the boolean variable is false (this if statement belongs at the end of your game loop) you call Stop(arg)/clearInterval(arg). Given that your current code doesn't seem to have a global boolean variable indicating game state (using an enumeration would generally be a cleaner solution but a simple boolean seems to suit this case)

Java Script Slide Show (add slide effect)

I have a problem
this are my first steps in javascript and I'm trying to make a Javascript slide show.
I try to add a "slide in" "slide out" effect
But I don't know how I can do this.
I google about 2-3 hours but still no solution.
Please help me and give me some feedback please
Here is my code
<head>
<title>Test Slider</title>
</head>
<body>
<div id="slider" style="width: 400px; height: 200px;color: orange; font-weight: bold; font-size: 30px;font-family: sans-serif" onclick="javascript:superlink()" style="cursor:pointer;"></div>
<script type="text/javascript">
//Init//
var SlideDauer = 2000;
var ImgInX = 0;
var ImgInXposition = 0;
var background = 'url(http://www.flashforum.de/forum/customavatars/avatar47196_1.gif)';
var SldInX = 0;
var LinkInX = 0;
function superlink() {
if (!SliderKannEsLosGehen()) return false;
if (LinkInX >= SliderBilder.length) {
LinkInX = 0;
}
var Ziel = window.location.href = SliderLink[LinkInX];
++LinkInX;
}
var SliderBilder = new Array();
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
SliderBilder.push("http://bytes.com/images/bytes_logo_a4k80.gif");
SliderBilder.push("http://cdn.qservz.com/file/df8e9dcf202cfddedf6f2d4d77fcf07b.gif");
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
//SliderBilder.push("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
var SliderTitle = new Array();
SliderTitle.push("");
SliderTitle.push("Title 1");
SliderTitle.push("Title 3");
SliderTitle.push("Title 4");
//SliderTitle.push("Title 5");
var SliderLink = new Array();
SliderLink.push("http://www.google.de");
SliderLink.push("http://spiegel.de");
SliderLink.push("http://bing.com");
SliderLink.push("http://youtube.com");
//SliderLink.push ("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
function SliderKannEsLosGehen() {
if (SliderBilder.length < 2) return false;
return true;
if (SliderTitle.length < 2) return false;
return true;
}
//Run//
function SliderRun() {
if (!SliderKannEsLosGehen()) return false;
if (ImgInX >= SliderBilder.length) {
ImgInX = ImgInXposition;
}
if (SldInX >= SliderBilder.length) {
SldInX = 0;
}
document.getElementById("slider").style.backgroundImage = 'url(' + SliderBilder[ImgInX] + ')';
++ImgInX;
document.getElementById("slider").innerHTML = SliderTitle[SldInX];
++SldInX;
window.setTimeout("SliderRun()", SlideDauer);
}
window.setTimeout("SliderRun()", SlideDauer);
</script>
</body>
</html>
For effects i would look into JQuery and use the animate function. There is loads of fun to be had with this as long as you have an understanding of css.

Categories