RUG-question123
RUG-question123

Reputation: 11

How to show div element when a certain variable is chosen?

I am doing a school project and I have to make a web-based browser game. Now I want DIV A to appear when someone chooses player 1, and DIV B to appear when a user chooses player 2. I cannot seem to work it out. Here is what I have got so far. I'm not quite good in JS, I hope somebody can help me out! I defined the players at index.php, like this:

<?php

session_start();

header('Content-Type: application/json');

$playerId = $_SESSION['playerId'];
$username = $_SESSION['username'];

if (!isset($playerId) || !isset($username)) {
    echo json_encode(['error' => 'Session not defined!']);
    die;
}

echo json_encode(['success' => true, 'data' => [
    'playerId' => $playerId,
    'username' => $username,
]]);

Then, later onwards, this is the code that I want to work on the game.php page:

The JS part

// player display
var player = ['1', '2'];


if (player == '1') {
    // display #divA
} else {
    // display #divB
}

The html part

<div id="questionarea" style="display:none;">
    <label for="question"></label>
    <textarea name="question" id="question" placeholder="Typ hier je vraag...">
    </textarea>
    <button type="button" id="send_chat">Button</button>
</div>
<div class="divB" style="display:none;">
    <button class="col-3" type="button" id="yes">yes</button>
    <button class="col-3" type="button" id="no">no</button>
    <button class="col-3" type="button" id="maybe">maybe</button>
</div>
<br/>
<div class="divA" style="display:none;">
    <button class="col-3" type="button" id="winner" onclick="won_alert()">you won!</button>
</div>

Upvotes: 1

Views: 45

Answers (3)

Ashin Ashok
Ashin Ashok

Reputation: 111

You can use jquery here

if (player == '1') {
    $('.divA').css('display','block');
    $('.divB').css('display','none');
} else {
    $('.divB').css('display','block');
    $('.divA').css('display','none');
}

Upvotes: 0

Sanmeet
Sanmeet

Reputation: 1410

You can use element.style property to change the styles or element.classList to add or remove the class which can help in displaying stuff based on logic

if(player == "1"){
  document.querySelector('.divA').style.display = "block";
  document.querySelector('.divB').style.display = "none" ;
  }else{
  document.querySelector('.divA').style.display = "none";
  document.querySelector('.divB').style.display = "block" ;
  }
  
  

Upvotes: 1

Shashank Ks
Shashank Ks

Reputation: 690

You can add a hidden attribute with a condition to the div:

<div [hidden]="player==1"></div>

The div is not shown if the condition inside the double quotes is true

Upvotes: 0

Related Questions