JavaScript: Problems in Snakes and Ladders Game [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to JavaScript. I am making Snakes and Ladders game. I am facing some problems on the code.
First I can not store the current position of the player so I can count the next destination.
The dice starts with 1 at the beginning of the game and this causes the player to start from the second cell.
The big snake and ladder divs displayed onto the board are not auto fit to the size of the board.
Here is the code I wrote so far Snakes and Ladder Game
var gameBoard = {
createBoard: function(dimension, mount) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = '100';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = '1';
return gameBoard;
}
};
gameBoard.createBoard(10, "#grid");
function intialPosition() {
$("#1").append($("#player1"));
$("#1").append($("#player2"));
var currentPosition = parseInt($("#1").attr('id'));
return currentPosition;
}
var w = intialPosition();
var face1 = new Image()
face1.src = "http://s19.postimg.org/fa5etrfy7/image.gif"
var face2 = new Image()
face2.src = "http://s19.postimg.org/qb0jys873/image.gif"
var face3 = new Image()
face3.src = "http://s19.postimg.org/fpgoms1vj/image.gif"
var face4 = new Image()
face4.src = "http://s19.postimg.org/xgsb18ha7/image.gif"
var face5 = new Image()
face5.src = "http://s19.postimg.org/lsy96os5b/image.gif"
var face6 = new Image()
face6.src = "http://s19.postimg.org/4gxwl8ynz/image.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
var random1 = rollDice();
var destination = w + random1;
function move() {
$('#' + destination).append($("#player1"));
var x = parseInt($('#' + destination).attr('id'));
var random = rollDice();
destination = x + random;
//alert(x);
return destination;
}
$(document).ready(function() {
//$('#' + destination).delay(100).fadeOut().fadeIn('slow');
$('#' + destination).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
});
var next = move();
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#100 {
background-image: url('http://s19.postimg.org/ceioc1g8v/rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="http://s19.postimg.org/otai9he2n/oie_e_RDOY2iqd5o_Q.gif" />
</div>
<div id="bigSnake">
<img src="http://s19.postimg.org/hrcknaagz/oie_485727s_RN4_KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="newGame" onClick="gameVM.newGame();">New Game</button>
</div>
<div>
<button type="button" name="reset" onClick="gameVM.defaultSetup()">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
</div>
</div>
</div>
</body>
Can anyone help me on that? Thanks in advance

To store the user current position , maintain the separate variable for storing the destination of diff player.
To start the play from the 1 , remove intialPosition() and make var w=0 , so once you call the rolldice() , it will start from 0.
In order to auto fit based on the change in screen size , use the bootstrap div which can auto fit the size of the div. Here is the link for it http://getbootstrap.com/css/#grid

Related

JavaScript itareate over divs and create a new one if doesn't fits

Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.

Move div to certain table cell according to random number [duplicate]

This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.

Resetting timer and score values to 0 before a new game starts

Im new to this but I've been having some trouble with trying to get my timer and score values back to 0 before a new game of memory starts. The values do reset, but don't show it until that value is affected. For example, the value for the number of matches never goes back to 0, it stays on 10(the max number of pairs) until you find the first match of the next game where it will then turn to 1. Does anybody know how to get the values to show 0 again when a new board is called up instead of just resetting when that value is affected?
I have already set
var turns = 0
var matches = 0
and called in them up as 0 in the function newBoard().
My timer code is:
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
Where I have called up the resetTime() function in the function newBoard().
My full code is:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
matches = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>
Both of the variables you are settings are displayed in HTML span objects.
What seems to be happening is that when you reset the Javascript variable, the value is being changed, but the span object where it is displayed to the user is being left at its previous value until it needs to be updated again.
As far as I can tell, your objects have the ids: matchNumber and Count for the match and turn variables respectively. If this is the case, try changing your code to reset the values to zero in the HTML when the variables are reset to zero.
For example:
// Reset the Javascript Count
var turns = 0
// Reset the HTML object
document.getElementById('Count').innerHTML = 0;
// Reset the Javascript Match Count
var matches = 0
// Reset the HTML object
document.getElementById('matchNumber').innerHTML = 0;
If I failed to explain this well, please comment and I'll try to clarify further.
I am not 100% sure, but you can try replacing your function with this one:
function timedCount() {
if(c>10){
//flipBack();
resetTime();
return;
}
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}

How to rollover text on images dynamically using javascript/jquery

I am new to web development but highly fascinated by it. So, basically I am creating a light-box where thumbnails of images will be appear on screen and they will appear bigger in size when user clicks over them. Now, I want when user hovers over the gallery images/thumbnails then some text should appear over the current image with may be some animation or basically mouser-hover should cause some event to happen but I am unable to do it. Text should be added dynamically or may be previously stored in an array or something of that sort. Please have a look at my code and tell me how to modify it in order to achieve such effect and if you know a better and easier way to do so then feel free to share. Thank you so much!!
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
JAVASCRIPT:
var gallery_slider = new Array();
gallery_slider[0] = "im1.jpg";
gallery_slider[1] = "im2.jpg";
gallery_slider[2] = "im3.jpg";
function displayAllImages() {
var i = 0,
len = gallery_slider.length;
for (; i < gallery_slider.length; i++) {
var img = new Image();
img.src = gallery_slider[i];
img.style.width = '200px';
img.style.height = '120px';
img.style.margin = '3px';
img.style.cursor = 'pointer';
document.getElementById('images').appendChild(img);
}
};
$(function() {
displayAllImages();
});
$(function() {
$('img').click(function() {
var hell = (this).src;
display(hell);
});
});
function display(hello) {
$('header').css('display', 'none'); /*for some other purposes*/
$('.limage').html("<img src=" + hello + " >");
$('.lightbox').css("display", "block");
$('.lightbox').fadeIn();
$('.right').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p >= (im.length - 1)) {
p = -1;
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p + 1] + ">");
$('.limage').fadeIn(500);
hello = im[p + 1];
});
$('.left').click(function() {
var im = new Array();
var x;
var p;
for (x = 0; x < gallery_slider.length; x++) {
im[x] = gallery_slider[x];
}
for (p = 0; p < im.length; p++) {
if (im[p] == hello) {
break;
} else {
continue;
}
}
if (p == 0) {
p = (im.length);
}
$('.limage').fadeOut(0);
$('.limage').html("<img src= " + im[p - 1] + ">");
$('.limage').fadeIn(500);
hello = im[p - 1];
});
$('.close').click(function() {
$('.lightbox').fadeOut();
$('header').css('display', 'block'); /*for some other purposes*/
});
};
CSS:
.gallery {
width: 100%;
height: 400px;
overflow: hidden;
margin: auto;
}
.gallery ul {
list-style: none;
}
.lightbox {
background-color: rgba(0, 0, 0, 0.3);
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
z-index: 106;
}
.close {
color: #fff;
border: 1px solid #fff;
border-radius: 100px;
background-color: #000;
position: absolute;
top: 10px;
right: 20px;
padding: 10px;
font-family: firstfont;
font-size: 30px;
z-index: 101;
cursor: pointer;
}
.close:hover {
background-color: #ebebeb;
color: #000;
}
.left {
width: 50%;
height: 100%;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
.right {
width: 50%;
height: 100%;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
.limage {
position: relative;
margin: auto;
top: 17%;
left: 15%;
max-width: 90%;
max-height: 90%;
}
There might be some bugs in coding. Watch out.
This code is working for displaying images as thumbnails as a matrix and as slider in lightbox when clicked upon them. I am not able to figure out how to add hover functionality to initial thumbnails.
Jsfiddle :
http://jsfiddle.net/psd6cbd7/1/
I'd suggest putting a div inside the image div containing the text and then using CSS to hide/show it.
HTML:
<div class="gallery">
<ul id="images"></ul>
<div class="lightbox">
<div class='limage'>
<div class=".caption">Caption here</div>
</div>
<div class='left'>
</div>
<div class='right'>
</div>
<div class='close'>
x
</div>
</div>
</div>
CSS:
.limage { position: relative; }
.caption { display: none; }
.limage:hover .caption { display: block; position: absolute;}
Why you using array to store the images? Anyways, assume that you still using array, below is some example code that you want try:
HTML:
<ul id="images">
</ul>
<!-- assume this is the place that you want to display the caption -->
<div id="caption"></div>
Javascript:
var images = new Array();
images[0] = "p1.png";
images[1] = "p2.png";
images[2] = "p3.png";
images[3] = "p4.png";
var captions = new Array();
captions[0] = "Picture 1";
captions[1] = "Picture 2";
captions[2] = "Picture 3";
captions[3] = "Picture 4";
var x = $("#images");
var y = $("#caption");
const prefix = "image-";
if you are using HTML5:
for (var i = 0; i < images.length; i++) {
x.append("<img class='roll' src='" + images[i] + "' data-caption='" + captions[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
y.html($(this).attr("data-caption"));
});
If you want to backward compatible:
for (var i = 0; i < images.length; i++) {
x.append("<img id='" + prefix + i + "' class='roll' src='" + images[i] + "'>");
}
$(".roll").mouseover(function(){
//do whatever effect here when mouse over
var index = $(this).attr("id").substring(prefix.length);
y.html(captions[index]);
});
Hope that this will help.

javascript background image change using array

I am not exprienced javascript programmer so I try to play with javascript. I am trying to make a slideshow by clicking on a button. Function I am trying to make a function with array that holds the names of all the images and changing the background-image according to the index of the array. I did only this part of function yet and I cant get what is wrong.
function change(lol){
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(change === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
}
middle {
width:1262px;
height:550px;
background-color: white;
margin-left: -7px;
}
#vvvmiddle {
width:700;
height:400;
background-image:url('veni1.jpg');
margin: 20px 0px 0px 310px;
float:left;
}
#sipka {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px 410px 0px 0px;
}
#sipkatext {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 10px;
padding-top: 1px;
}
#sipkaurl {
text-decoration: none;
}
#sipka:hover {
background-color: #3399FF;
}
#sipka2:hover {
background-color: #3399FF;
}
#sipka2 {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px -100px 0px 0px;
}
#sipkatext2 {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 13px;
padding-top: 1px;
}
<div id="middle">
<div id="vvvmiddle">
<div id="sipka" onclick="change('left')">
<div id="sipkatext">
<</div>
</div>
<div id="sipka2" onclick="change('right')">
<div id="sipkatext2">></div>
</div>
</div>
</div>
A possible solution may be this one:
var img = ["img1.png", "img2.png", "img3.png"];
var len = img.length;
var url = 'Some url...';
var current=0;
var middle = document.getElementById("vvvmiddle");
middle.style.backgroundImage = "url(" + url + img[current] + ")";
function change(dir){
if(dir == "right" && current < len-1){
current++;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
} else if(dir == "left" && current > 0){
current--;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
}
}
See it in action, check here jsfiddle.
You can try with that:
function change(lol) {
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(lol === "right"){
index = (index + 1) % img.length;
} else {
index = (index + img.length - 1) % img.length;
}
middle.style.backgroundImage = img[index];
}
You are checking wrong variable in condition, it should be lol, not change:
if(lol === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
Also you should handle "last image" case like Nicolas suggests.

Categories

Resources