How can I update attributes with jQuery? - javascript

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>

You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)

Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

Related

Printing pictures from JavaScript

I´m trying to print two pictures 24 times in a christmas calendar. The pictures I´m trying to print are innhold.gif and luke.jpg. When you click on luke.gif it´s supposed to change to innhold.gif. This is gonna happen in sirkel-div. But it´s only white. I can´t find out whats wrong either by myself or by inspect in Google chrome.
My question is, how can I change this code so when people click on luke.jpg it changes to innhold.gif?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Westerdals julekalender 2017 - Din julekalender</title>
</head>
<body>
<!--Header-->
<header>
<h1>Westerdals julekalender 2017</h1>
</header>
<!--Meny-->
<nav>
<ul>
<li>Forsiden</li>
<li>Din julekalender</li>
</ul>
</nav>
<!--Content from cookie-->
<section>
<p id="cookie-innhold">Her kommer cookie-innhold</p>
</section>
<!--Kalenderen-->
<div id="kalender-div">
<p id="peker-info"></p>
</div>
<div id="luke-div"></div>
<script>
(function(){
//Array
let tekstArray = document.cookie.split("=");
let tekst = tekstArray[1];
let SirkelDiv = document.getElementById("sirkel-div");
let body = document.getElementsByTagName("body")[0];
let html = document.documentElement;
document.getElementById("cookie-innhold").innerHTML = " " + tekst;
//Style av kalender
for(let i = 0; i < 24; i++){
let nySirkel = document.createElement("div");
nySirkel.style.cssText = "width: 300px; height: 300px; backround-image: url('images/innhold.gif');";
nySirkel.style.cssText += "border: 2px solid black; opacity: 0.7;";
nySirkel.style.cssText += "border-radius: 50%; float: left; margin: 5px;";
nySirkel.innerHTML = (i + 1);
nySirkel.onclick = openLuke;
body.appendChild(nySirkel);
}
function openLuke(){
this.style.backgroundImage = "url('images/luke.jpg');";
}
}());//End function
</script>
</body>
</html>
Besides the typo you have in the cssText assignment, you are trying to set an invalid css property value
"url('images/luke.jpg');"
; is not valid as part of the backgroundImage property remove it. The browser is not assigning the value since it is invalid.
(function() {
let body = document.body;
//Style av kalender
for (let i = 0; i < 24; i++) {
let nySirkel = document.createElement("div");
nySirkel.style.cssText = "width: 300px; height: 300px; background-image: url('http://lorempixel.com/output/technics-q-c-640-480-1.jpg');";
nySirkel.style.cssText += "border: 2px solid black; opacity: 0.7;";
nySirkel.style.cssText += "border-radius: 50%; float: left; margin: 5px;";
nySirkel.innerHTML = (i + 1);
nySirkel.onclick = openLuke;
body.appendChild(nySirkel);
}
function openLuke() {
this.style.backgroundImage = "url('http://lorempixel.com/output/people-q-c-640-480-1.jpg')";
}
}()); //End function
<header>
<h1>Westerdals julekalender 2017</h1>
</header>
<!--Meny-->
<nav>
<ul>
<li>Forsiden</li>
<li>Din julekalender</li>
</ul>
</nav>
<!--Content from cookie-->
<section>
<p id="cookie-innhold">Her kommer cookie-innhold</p>
</section>
<!--Kalenderen-->
<div id="kalender-div">
<p id="peker-info"></p>
</div>
<div id="luke-div"></div>

Can't make 2 Player Tic Tac Toe game work JavaScript

HTML
<div class="container"> <-- div container -->
<div id="div1" onclick="canvasClicked(1);"></div>
<div id="div2" onclick="canvasClicked(2);"></div>
<div id="div3" onclick="canvasClicked(3);"></div>
<div id="div4" onclick="canvasClicked(4);"></div>
<div id="div5" onclick="canvasClicked(5);"></div>
<div id="div6" onclick="canvasClicked(6);"></div>
<div id="div7" onclick="canvasClicked(7);"></div>
<div id="div8" onclick="canvasClicked(8);"></div>
<div id="div9" onclick="canvasClicked(9);"></div>
</div> <-- div container end -->
Css
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}
.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}
JavaScript
var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;
var turn = 0;
var squaresFilled = 0; //global variables end
window.onload = function(){ //instantiating variables
painted = new Array(); //to check if the canvas contains something already
content = new Array(); //to see what the canvas contains 'X' or 'O'
winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P
for(var i=0; i<=8; i++){
painted[i] = false;
content[i]=false;
}
}
function canvasClicked(number){
theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);
if(painted[number-1]==false){
if(turn%2==0){ //use X here
c.innerHTML = '<img src="cross image" alt="x" width=100%
height=100%>';
content[number-1] = 'X'; //storing value in content array
}else{ // user O here
c.innerHTML = '<img src=" O image" height="100%"
width="100%" alt="O">';
content[number-1] = 'O'; //storing value in content array
}
}
else{
alert('This block is already occupied, try another block');
turn--;
squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);
if(squaresFilled == 9){
alert('It is a TIE');
playAgain();
}
}
function checkForWinner(symbol){ // This functions seems to be the problem
for(var a = 0; a < winningCombinations.length; a++){
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
console.log(symbol + ' won!!');
}
}
}
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks
In the function checkForWinner change:
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol &&
content[winningCombinations[a][2]]==symbol){
to:
if(content[winningCombinations[a][0]-1]==symbol &&
content[winningCombinations[a][1]-1]==symbol &&
content[winningCombinations[a][2]-1]==symbol){
It would make things easier if you numbered everything from 0 instead of 1. Then you don't need all those -1.
Check your indices.
Either content[0-8] or content[1-9]
winningCombination uses 1-9
but canvasClicked uses 0-8
That's why you getting some strange results
I know I should help you with your code, but I decided to use parts of your code and suggest you an approach:
HTML :
<div class="turnInfo" id="turnInfo">Turn : O</div>
<div class="container">
<div id="div1" cell="1" onclick="canvasClicked(this);"></div>
<div id="div2" cell="2" onclick="canvasClicked(this);"></div>
<div id="div3" cell="3" onclick="canvasClicked(this);"></div>
<div id="div4" cell="4" onclick="canvasClicked(this);"></div>
<div id="div5" cell="5" onclick="canvasClicked(this);"></div>
<div id="div6" cell="6" onclick="canvasClicked(this);"></div>
<div id="div7" cell="7" onclick="canvasClicked(this);"></div>
<div id="div8" cell="8" onclick="canvasClicked(this);"></div>
<div id="div9" cell="9" onclick="canvasClicked(this);"></div>
</div>
CSS :
.turnInfo{
text-align:center;
font-size:40px;
font-weight:bold;
margin-top: 6%;
margin-bottom:10px;
}
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
}
.container div{
float: left;
height: 102px;
width: 131.3px;
border: 1px solid black;
text-align:center;
padding-top:30px;
font-size:50px;
}
JS :
Variables
var cells = [0,0,0,0,0,0,0,0,0,0]; // make it 10 for the sake of array index
var turn = 'O'; // first turn : O
var infoDiv = document.getElementById('turnInfo');
Toggle the Trun
function toggleTurn(){
turn = turn == 'O' ? 'X' : 'O';
infoDiv.innerHTML = 'Turn : '+turn;
return turn;
}
Canvas Click Handler
function canvasClicked(cell){
var cellIndex = cell.getAttribute('cell');
if(!cells[cellIndex]){
cells[cellIndex] = toggleTurn();
cell.innerHTML = turn; // you can add image here.
checkWinner();
}
}
Check Result function
function checkWinner(){
winningCombinations = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7]
]; //all possible combinations :P
for(var index=0; index < winningCombinations.length;index++){
winCond = winningCombinations[index];
if(cells[winCond[0]] != 0 &&
cells[winCond[0]] == cells[winCond[1]] &&
cells[winCond[1]] == cells[winCond[2]])
{
alert(turn + ' is winner');
playAgain();
return;
}
}
var allCellsFilled = 1;
for(var index =1; index < cells.length; index++){
if(!cells[index]){
allCellsFilled = 0;
break;
}
}
if(allCellsFilled){
alert('Game is draw!');
playAgain();
}
}
New Game function
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
You can see it here : https://codepen.io/FaridNaderi/pen/awROjY
Hope it helps.

Having trouble restarting logic Tic Tac Toe game (JavaScript)

I am having trouble to look where the problem is.
I was able to create the game board and I will be implementing AI soon.
For now, I need to make it work so that everytime the game is over, it will restart a new one and resume.
However when it reaches to that point, it stops working.
From my what I've read, I may not be binding the events correctly, but I am still left puzzled.
Can anyone pinpoint what is wrong with my code?
$(document).ready(function(){
var human;
var computer;
var board = new Board()
var game;
function Human(symbol){
this.name = "Player",
this.symbol = symbol;
}
function Computer(symbol){
this.name = "Computer",
this.symbol = symbol;
}
//Modal opens when page is rendered. User can choose symbol
$("#myModal").modal()
$("#xPlayer").on('click',function(){
human = new Human("X");
computer = new Computer("O");
board.initalize();
game = new Game(human)
game.play();
})
$("#oPlayer").on('click',function(){
human = new Human("O")
computer = new Computer("X");
board.initalize();
game = new Game(computer)
game.play();
})
//Board constuctor
function Board(){
this.board = []
this.status = "";
}
//method calls for an empty board filled with "E"
Board.prototype.initalize = function(){
$("td p").empty()
this.board = ["E","E","E","E","E","E","E","E","E"]
this.status = "New Game";
}
//return true if there is a win. Otherwise, false
Board.prototype.win = function(){
var B = this.board;
//check row
for (var i = 0; i <= 6; i = i + 3){
if (B[i] !== "E" && (B[i] === B[i+1]) && (B[i+1] === B[i+2])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check column
for (var i = 0; i <= 2 ; i++ ){
if (B[i] !== "E" && (B[i] === B[i+3]) && (B[i+3] === B[i+6])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check diagonal
for(var i = 0, j = 4; i <= 2 ; i = i + 2, j = j - 2) {
if(B[i] !== "E" && (B[i] == B[i + j]) && (B[i + j] === B[i + 2 * j]) ) {
board.status = "Winner is: " + game.currentPlayer.name
return true;
}
}
return false
}
//checks if the current status is draw. If so, updates the status to "Draw"
Board.prototype.draw = function(){
//checks if the board itself is draw
for(var i = 0; i < this.board.length ; i++){
if (this.board[i] === "E"){
return false;
}
}
board.status = "Draw!"
return true;
}
//method returns array of indexes that are not empty cells in the board
Board.prototype.available = function(){
var B = this.board;
var indexes = [];
for (var i = 0; i < B.length ; i ++){
if (B[i] === "E"){
indexes.push(i)
}
}
return indexes;
}
//checks first if the User Input is valid or not
Board.prototype.validMove = function(position){
var availableCells = this.available();
return availableCells.includes(position);
}
//updates the board when using jQuery click
//it will render the webpage by prototype_writeBoard
Board.prototype.updateBoard = function(position,playerInput) {
var availableCells = this.available();
if (availableCells.includes(position)){
this.board[position] = playerInput
}
};
function Game(firstPlayer){
this.currentPlayer = firstPlayer;
this.over = false;
this.win = "";
}
Game.prototype.switchPlayer = function(){
this.currentPlayer = (this.currentPlayer === human) ? computer : human
}
Game.prototype.play = function(){
$("td").click(function(){
var position = $(this).attr("id");
var positionNumber = parseInt(position.slice(4,5))
// This here renders to the board and updates board.board
if(board.validMove(positionNumber)){
//Checks if the move is valid. If it is, append it.
//Otherwise, alert the user that it is taken
$(this).find("p").append(game.currentPlayer.symbol)
board.updateBoard(positionNumber, game.currentPlayer.symbol)
//Check if it the game is over or draw
//If either is true, play new game
if (board.win() || board.draw()){
alert(board.status)
game.restart();
}
game.switchPlayer();
}else{
alert("Already taken")
}
})
}
Game.prototype.restart = function(){
board.initalize();
game.play()
}
})
body {
background: skyblue; }
#tictactoe {
max-width: 700px;
min-height: 300px;
margin: 68px auto;
display: flex;
width: 100%; }
#tictactoe table {
width: 100%;
font-size: 65px;
text-align: center;
vertical-align: middle;
table-layout: fixed; }
td {
height: 115px;
color: #101935;
background: #F2FDFF;
border: 5px solid #DBCBD8;
border-radius: 12px;
cursor: pointer;
transition: background 0.5s ease-out, color 0.5s ease-out; }
td:hover {
background: #564787;
color: #F2FDFF; }
.modal-dialog {
text-align: center; }
.modal-dialog .modal-footer {
text-align: center; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TicTacToe FCC</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="css/styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="tictactoe">
<table id="game-board">
<tbody>
<tr id="row1">
<td id="cell0"><p></p></td>
<td id="cell1"><p></p></td>
<td id="cell2"><p></p></td>
</tr>
<tr id="row2">
<td id="cell3"><p></p></td>
<td id="cell4"><p></p></td>
<td id="cell5"><p></p></td>
</tr>
<tr id="row3">
<td id="cell6"><p></p></td>
<td id="cell7"><p></p></td>
<td id="cell8"><p></p></td>
</tr>
</tbody>
</table>
</div>
<!--Modal Window -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Choose your character!</h4>
</div>
<div class="modal-body">
<p>Have fun!</p>
</div>
<div class="modal-footer">
<button type="button" id="xPlayer" class="btn btn-default" data-dismiss="modal">X</button>
<button type="button" id="oPlayer" class="btn btn-default" data-dismiss="modal">O</button>
</div>
</div>
</div>
</div>
</body>
<script src="js/javascript.js" type="text/javascript"></script>
</html>
In Game.play you are binding to the onclick of the td element. Then in Game.restart you are calling Game.play which is binding to the click event again. Since you are already calling Game.play when you setup the players there is no need to call it in Game.restart since it is still bound to the click event
Game.prototype.restart = function(){
board.initalize();
/* delete-me game.play() */
}

How to dynamically create table in html with certain constraints?

i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>

Random card/Image using buttonjavascript

I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.

Categories

Resources