Raven Taylor
Raven Taylor

Reputation: 23

Displaying Images in a DIV onClick

I have to make a connect four style game for a course I am doing.

At the moment when a player clicks a square on the grid, it fills that square with either an X or a O depending on which player has been assigned what.

The final thing I need to do is have the grid square display and image (either red or green) in the square instead of the text. This is the small section of the code that is displaying the text of either X or 0 which I need to somehow change to display an image instead. This is part of a wider onClick function which happens whenever a player clicks on a grid square.

if (turn == player1Name) {
  moveCount++;
  $(this).text("0");
  grid[row][col] = 1;
  var ifWon = winnerCheck(1,player1Name);
}

Upvotes: 2

Views: 70

Answers (3)

KCB4Rockstar
KCB4Rockstar

Reputation: 1

I'm not sure how your HTML for this is laid out, but there are two ways you can get the div red or green.

The first way is, as you said, displaying an image in the div onClick. To do this, target the div you want to have the image, then insert/remove the specific image element you want.

if(turn == player1Name){ 
    moveCount++;
    $(this).append("<img class="myImg" src="public/green.png" alt="green"/>);
    grid[row][col] = 1;
    var ifWon = winnerCheck(1,player1Name);

You can also have the image in the div by default and toggle it to display or not

if(turn == player1Name){ 
    moveCount++;
    $(this).find(".myImg").css("display", "none"); //or css("opacity", "0") depending how you wrote your html
    grid[row][col] = 1;
    var ifWon = winnerCheck(1,player1Name);

The second way is not using images, but instead just changing the background colour of the div when selected.

if(turn == player1Name){ 
    moveCount++;
    $(this).css("background-color", "green");
    grid[row][col] = 1;
    var ifWon = winnerCheck(1,player1Name);

Upvotes: 0

BloodyMonkey
BloodyMonkey

Reputation: 1634

I suggest you to create 2 classes, one for X and one for O

.cross{
background-image: url('cross.png');
background-size: cover
}

Then you change the class of the square

$(this).addClass( "cross" )

instead of

$(this).text("0");

Upvotes: 1

cssyphus
cssyphus

Reputation: 40030

You can use .html() to display HTML tags instead of just text. So,

if (turn == player1Name) {
  moveCount++;
  $(this).html('<img src="http://placekitten.com/50/50" />');
  grid[row][col] = 1;
  var ifWon = winnerCheck(1,player1Name);
}

If you wish to use a .jpg or .png file somewhere on your filesystem, you would just substitute the path to that file (relative to the location of the file running the above code):

  $(this).html('<img src="img/redcircle.jpg" />');

or (if your js code is in a subfolder):

  $(this).html('<img src="../img/redcircle.jpg" />');

or (if the img file is in the same folder as your index.html):

  $(this).html('<img src="redcircle.jpg" />');

Upvotes: 0

Related Questions