Changing style of unknown element in JavaScript - javascript

I'm trying to build a tic-tac-toe game where the user first clicks which player he wants to be, then clicks on the square in the board where he wants to play. The issue I'm having is changing the background of the square that the user clicks. Because I don't know which square the user will click, I can't figure out how to change the style of the background, because the square's id/class is unknown.
I can't say:
document.getElementById("randomId").style.backg round
because I don't know which square the user will click. Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style type="text/css">
#buttons{
margin-top: 50px;
}
#x{
margin-left: 10px;
}
#table{
margin-top: 15px;
background: gray;
table-layout: fixed;
width: auto;
width: 250px;
height: 250px;
}
</style>
</head>
<body>
<div class="container" id="buttons">
<h2 id="h2">Choose your team!</h2>
<button onclick="myFunctions()" type="button" class="btn btn-default"><span
style="font-weight: bold; font-size: 110%;">O</span></button>
<button type="button" id="x" class="btn btn-default"><span class="glyphicon glyphicon-remove"></span>
</button>
<table id="table" class="table table-bordered">
<tbody>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var master = false;
var servant = false;
function myFunctions(){
master = true;
}
function myFunction() {
if (master == true) {
}
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

Well, you could either do it like this, where you add an argument when you call the function, in this case the this keyword would point to the html element (td).
By adding a css class, you can handle the changes relatively easily and check if it wasn't clicked before.
var master = true;
// clickedElement = your dom element you want to update
function myFunction(clickedElement) {
// if a dom element was given and it doesn't have a className yet
if (clickedElement && !clickedElement.className) {
// set a class on the element
clickedElement.className = master ? 'master' : 'servant';
// change the player (if it's not a master it's a servant)
master = !master;
}
}
#buttons {
margin-top: 50px;
}
#x {
margin-left: 10px;
}
#table {
margin-top: 15px;
background: gray;
table-layout: fixed;
width: auto;
width: 250px;
height: 250px;
}
.master {
background-color: green;
}
.servant {
background-color: red;
}
<div class="container" id="buttons">
<h2 id="h2">Choose your team!</h2>
<button onclick="myFunctions()" type="button" class="btn btn-default"><span style="font-weight: bold; font-size: 110%;">O</span>
</button>
<button type="button" id="x" class="btn btn-default"><span class="glyphicon glyphicon-remove"></span>
</button>
<table id="table" class="table table-bordered">
<tbody>
<tr>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
</tr>
<tr>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
</tr>
<tr>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
<td onclick="myFunction(this)"></td>
</tr>
</tbody>
</table>
</div>
There is of course no reason to only store this information on the DOM, you would still have to evaluate if there were 3 cells of the same color. You might want to choose to keep a data structure that checks which block was clicked and who clicked it and if there are diagonally, vertically or horizontally 3 in a row for the person who just clicked.
and if you want some more inspiration, you can check this jsfiddle

Related

How to replace a text from a dynamic table into a picture

On my site I have a scoreboard that receives it's info from a other website, so the content is dynamic.
I am trying to replace parts of the content of a table with pictures. So that instead of the 3 letterword of a club the logo appears. But my knowledge of CSS an Jquery is not large enough.
Can someone help my with the CSS or other html language parts?
This is the content that generates the table:
<style>
table,
td,
th {
border: 1px solid #ddd;
text-align: center;
font-size: 15px;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 1px;
}
th {
background-color: #c71b1b
}
th,
td1 {
padding: 1px;
}
th {
background-color: #c71b1b
}
</style>
<div style="overflow-x:auto;">
<table cellspacing="20">
<tbody>
<tr>
<th colspan="5">
<h1>MANNEN</h1>
</th>
</tr>
<tr>
<td width=14%>DATUM</td>
<td width=13%>UUR</td>
<td width=12%>THUIS</td>
<td width=12%>UIT</td>
<td width=49%>SCORE</td>
</tr>
</tbody>
</table>
<table cellspacing="20">
<tbody>
<tr>
<div class="pb-dynamic" id="block-main-men">
<p><img src="//www.pointbench.com/pointbench/img/pb-loading-1.gif" /></p>
</div>
</tr>
</tbody>
</table>
<table cellspacing="20">
<tbody>
<tr>
<th colspan="5">
<h1>VROUWEN</h1>
</th>
</tr>
<tr>
<td width=14%>DATUM</td>
<td width=13%>UUR</td>
<td width=12%>THUIS</td>
<td width=12%>UIT</td>
<td width=49%>SCORE</td>
</tr>
</tbody>
</table>
<table cellspacing="20">
<tbody>
<tr>
<div class="pb-dynamic" id="block-main-women">
<p><img src="//www.pointbench.com/pointbench/img/pb-loading-1.gif" /></p>
</div>
</tr>
</tbody>
</table>
</div>
<!-- Include JS script to do the job, block definition(s) and main function call -->
<script src="//stats.pointbench.com/pointbench/js/pb-update-ex.js" type="text/javascript"></script>
<script type="text/javascript">
<!--//--><![CDATA[// ><!--
blockdefs = [{
leagueid: 'bel/29/2022',
blocktype: 'team-games',
target: 'block-main-men',
teamid: '413'
},
{
leagueid: 'bel/30/2022',
blocktype: 'team-games',
target: 'block-main-women',
teamid: '207'
}
];
PBShowBlocks(blockdefs);
//--><!]]>
</script>
<!-- End -->
</div>
</div>
Your table stucture doesn't follow the expected pattern. Maybe the browser is also rewriting the tags to match the correct hierarchy, what "breaks" the selector logic inside the image replacer function.
Try:
<table cellspacing="20">
<tbody>
<tr>
<td>
<div class="pb-dynamic" id="block-main-women">
<p><img src="//www.pointbench.com/pointbench/img/pb-loading-1.gif" /></p>
</div>
</td>
</tr>
</tbody>
</table>
EDIT: I see how the code is supposed to work now. See edited code below.
You're not including the src tags correctly. In every script and image tag, you included something like "//google.com". That's not a valid URL. Usually, if you're fetching from another URL, you put something like src="https://google.com/"
The JS file you linked has an error in it. You can see it if you open the console. It's not using the proper path for the css file. It's saying the path for the css file pb-blocks.css is at stats.pointbench.com/css/pb-blocks.css but I'd bet it's actually at, following the same path structure as the JS file, stats.pointbench.com/pointbench/css/pb-blocks.css https://stats.pointbench.com/pointbench/css/pb-blocks.css
If you have access to that server, you can fix it there, but if not, I'll put a fix at the end.
Okay since the JS file is broken, just go to the url for the JS file and copy and paste the content and put it in your public/assets route.
Ctrl-F and find every instance of document.getElementsByTagName("head")[0].appendChild(fileref); On the line above it, you'll see fileref.setAttribute("href", gUpdateDomain + "pointbench/css/pb-blocks.css"); Replace it with this line: fileref.setAttribute("href", "https://stats.pointbench.com/pointbench/css/pb-blocks.css");
There should be two instances of this.
Also, your table structure is invalid. Below is the proper table structure
<table cellspacing="20">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
Overall, your code just needs a little touch up to make it look pretty. I removed the unnecessary elements and the closing tags with no open tags. See code below:
<style>
table, td, th {
border: 1px solid #ddd;
text-align: center;
font-size: 15px;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 1px;
}
th{
background-color: #c71b1b
}
th, td1 {
padding: 1px;
}
th{
background-color: #c71b1b
}
</style>
<div style="overflow-x:auto;">
<table cellspacing="20">
<thead>
<tr colspan="5">
<th><h1>MANNEN</h1></th>
</tr>
</thead>
<tbody>
<tr>
<td width=14%>DATUM</td>
<td width=13%>UUR</td>
<td width=12%>THUIS</td>
<td width=12%>UIT</td>
<td width=49%>SCORE</td>
</tr>
<tr>
<div class="pb-dynamic" id="block-main-men">
<p><img src="https://pointbench.com/pointbench/img/pb-loading-1.gif" /></p>
</div>
</tr>
</tbody>
</table>
<table cellspacing="20">
<thead colspan="5">
<th colspan="5">
<tr><h1>VROUWEN</h1></tr>
</th>
</thead>
<tbody>
<tr>
<td width=14%>DATUM</td>
<td width=13%>UUR</td>
<td width=12%>THUIS</td>
<td width=12%>UIT</td>
<td width=49%>SCORE</td>
</tr>
<tr>
<div class="pb-dynamic" id="block-main-women">
<p><img src="https://pointbench.com/pointbench/img/pb-loading-1.gif" /></p>
</div>
</tr>
</tbody>
</table>
</div>
<!-- <script src="script.js" type="text/javascript"></script> -->
<script src="https://stats.pointbench.com/pointbench/js/pb-update-ex.js" type="text/javascript"></script>
blockdefs =
[
{
leagueid: 'bel/29/2022',
blocktype: 'team-games',
target: 'block-main-men',
teamid: '413'
},
{
leagueid: 'bel/30/2022',
blocktype: 'team-games',
target: 'block-main-women',
teamid: '207'
}
];
PBShowBlocks( blockdefs );
</script>
As for your question, replacing team initials with a team logo is possible and doable. But to do this, you need to have the team logos stored somewhere, or fetch them from a server using API. Assuming there's only a couple of team logos, you can easily download them all and store them, then replace the initials with a logo.
For this example I'm gonna use a URL of a logo from the internet.
Say we have a table like the one you have, I don't know which cell in your table is a team name. But let's assume it's the 2nd and 3rd cell in every row.
I'd write some code like this:
<table cellspacing="20">
<thead>
<th colspan="5">
<tr><h1>MANNEN</h1></tr>
</th>
</thead>
<tbody id="mensteam">
<tr>
<td width=14%>DATUM</td>
<td width=13%>RM</td>
<td width=12%>FCB</td>
<td width=12%>UIT</td>
<td width=49%>SCORE</td>
</tr>
</tbody>
</table>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function setLogo(teaminitials) {
switch(teaminitials)
{
case "RM":
var src = "https://www.freepnglogos.com/uploads/real-madrid-logo-png/real-madrid-logo-large-images-3.png";
break;
case "FCB":
var src = "https://pngimg.com/uploads/poop/poop_PNG52.png";
break;
}
return src;
}
$(document).ready(function(){
const menTable = $('#mensteam');
$('#mensteam tr').each(function(){
//first team
var teamName = $(this).children('td:nth-child(2)');
var logo = setLogo(teamName.text());
teamName.text("");
teamName.prepend('<img style="max-width: 10%;" src="' + logo + '" >');
//second team
var teamName2 = $(this).children('td:nth-child(3)');
var logo2 = setLogo(teamName2.text());
teamName2.text("");
teamName2.prepend('<img style="max-width: 10%;" src="' + logo2 + '" >');
});
});
</script>
Before
After

JavaScript table

I need help with this question:
I have created the table but I don't know how to use the event inside it
<table style="width: 337px; margin-left: auto; margin-right: auto;" border="1">
<tbody>
<tr>
<td style="width: 90px;" colspan="9">
<table style="width: 329px;" border="1">
<tbody>
<tr>
<td style="width: 105.6875px;"> Skating</td>
<td style="width: 110.3125px;"> Swimming</td>
<td style="width: 130px;"> Cooking</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="text-align: center;">
<td style="width: 90px;" colspan="9">
<p>Hover Over Hobby Name to See Image</p>
</td>
</tr>
</tbody>
</table>
<br>
<style>
div {
text-align: center;
}
table {
border-collapse: collapse;
}
</style>
Thank you in advance.
You got the idea...
<table style="width: 337px; margin-left: auto; margin-right: auto;" border="1">
<tbody>
<tr>
<td style="width: 90px;" colspan="9">
<table style="width: 329px;" border="1">
<tbody>
<tr>
<td style="width: 105.6875px;"> Skating</td>
<td style="width: 110.3125px;"> Swimming</td>
<td style="width: 130px;"> Cooking</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="text-align: center;">
<td style="width: 90px;" colspan="9">
<p>Hover Over Hobby Name to See Image</p>
</td>
</tr>
</tbody>
</table>
<br>
<style>
div {
text-align: center;
}
table {
border-collapse: collapse;
}
</style>
const hobies = document.querySelector('[hobies]')
const hoby_image = document.querySelector('[hoby-image]')
var hoby_images = {
'Skating': 'https://picsum.photos/id/237/200/300',
'Swimming': 'https://picsum.photos/id/238/200/300',
'Cooking': 'https://picsum.photos/id/239/200/300'
}
for(let i = 0; i < hobies.childElementCount; i++){
hobies.children[i].addEventListener('mouseover', ()=>{
hoby_image.children[0].src = `${Object.entries(hoby_images)[i][1]}`
})
}
td{
cursor:pointer;
}
td:hover{
border:red;
}
div {
text-align: center;
}
table {
border-collapse: collapse;
}
<table style="width: 337px; margin-left: auto; margin-right: auto;" border="1">
<tbody>
<tr>
<td style="width: 90px;" colspan="9">
<table style="width: 329px;" border="1">
<tbody>
<tr hobies>
<td style="width: 105.6875px;">Skating</td>
<td style="width: 110.3125px;">Swimming</td>
<td style="width: 130px;">Cooking</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="text-align: center;">
<td hoby-image style="width: 90px;" colspan="9">
<img src='https://picsum.photos/id/237/200/300'></img>
</td>
</tr>
</tbody>
</table>
<br>
First, for each td tag you want to have the "mouseover" event, you need to add the event handler.
<tr class="hobbies">
<td style="width: 105.6875px" onmouseover="changeImg('skating')">
Skating
</td>
<td style="width: 110.3125px" onmouseover="changeImg('swimming')">
Swimming
</td>
<td style="width: 130px" onmouseover="changeImg('cooking')">
Cooking
</td>
</tr>
For the style just use this
<style>
div {
text-align: center;
}
.hobbies td:hover {
cursor: pointer;
color: red;
}
</style>
Then at the second row change p tag with an img tag
<!-- Change the src attribute onmouseover -->
<img id="imgToChange" src="skating.jpg" alt="skating" />
At the bottom add this script
<script>
const changeImg = (src) => {
let img = document.getElementById("imgToChange");
switch (src) {
case "skating":
img.src = "skating.jpg";
img.alt = "skating";
break;
case "swimming":
img.src = "swimming.jpg";
img.alt = "swimming";
break;
case "cooking":
img.src = "cooking.jpg";
img.alt = "cooking";
}
};
</script>
Base on which td tag is hovering, you can set the src and alt attribute of img tag with parameter.
const changeImg = (src) => {
let img = document.getElementById("imgToChange");
switch (src) {
case "skating":
img.src = "skating.jpg";
img.alt = "skating";
break;
case "swimming":
img.src = "swimming.jpg";
img.alt = "swimming";
break;
case "cooking":
img.src = "cooking.jpg";
img.alt = "cooking";
}
};
div {
text-align: center;
}
.hobbies td:hover {
cursor: pointer;
color: red;
}
<table style="width: 337px; margin-left: auto; margin-right: auto" border="1">
<tbody>
<tr>
<td style="width: 90px" colspan="9">
<table style="width: 329px" border="1">
<tbody>
<tr class="hobbies">
<td style="width: 105.6875px" onmouseover="changeImg('skating')">
Skating
</td>
<td style="width: 110.3125px" onmouseover="changeImg('swimming')">
Swimming
</td>
<td style="width: 130px" onmouseover="changeImg('cooking')">
Cooking
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="text-align: center">
<td style="width: 90px" colspan="9">
<!-- Change the src attribute onmouseover -->
<img id="imgToChange" src="skating.jpg" alt="skating" />
</td>
</tr>
</tbody>
</table>
<br />
Rather than use tables to do the layout (1992 called and wants a word with you) I've re-written using divs, but the concepts are exactly the same.
Attach the event handler .addEventListener for the mouseover event — you would attach it to your <td...> elements instead of my <li> elements.
I have attached which image to use to the element being hovered using a data- attribute, so the handler just gets that value and doesn't have to figure out which of the items is being hovered.
const imageHolder = document.querySelector('#imageholder img');
const hobbies = document.querySelectorAll('#hobbies li');
hobbies.forEach(el =>
el.addEventListener('mouseenter', function(e) {
const hobbyImage = e.target.dataset.image;
imageHolder.src = `https://picsum.photos${hobbyImage}`;
})
);
#app {
width: 80%;
}
#imageholder {
width: 90%;
margin: 0 auto;
}
ul#hobbies {
list-style-type: none;
}
ul li {
display: inline-block;
width: 30%;
text-align: center;
}
li + li {
border-left: 1px solid green;
}
<div id="app">
<ul id="hobbies">
<li data-image="/300/200">Skating</li>
<li data-image="/300/201">Swimming</li>
<li data-image="/300/202">Cooking</li>
</ul>
<div id="imageholder">
<img src="https://picsum.photos/300/200">
</div>
</div>

Remove parent div class if child div has a specific value

I have the following code:
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">16</button>
</td>
Check button value if it is 16 then remove the .CalendarDay--valid from the parent div.
How do I do this?
You can use closest() method to do that:
var elem = $('.CalendarDay__button');
if (elem.text().trim() === '16') {
elem.closest('.CalendarDay--valid').removeClass('CalendarDay--valid');
}
.CalendarDay--valid button{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">16</button>
</td>
</tr>
</table>
Use parent with this for particular td. I give two td 16 -- 17 on example.17 is shown but 16 remove.
$('.CalendarDay').find('.CalendarDay__button').each(function() {
if ($(this).text() == '16')
$(this).parent('td').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">16</button>
</td>
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">17</button>
</td>
</tr>
</table>
Try this if you have multiple buttons to check:
$.each($('.CalendarDay__button'),function(){
var btn = $(this);
var parent = btn.closest('.CalendarDay');
// Before
console.log(parent.attr('class'))
if(btn.text() == "16"){
parent.removeClass('CalendarDay--valid');
// After
console.log(parent.attr('class'))
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="CalendarDay CalendarDay--valid" style="width: 37px; height: 36px;">
<button type="button" class="CalendarDay__button">16</button>
</td>
</tr>
</table>

Javascript onclick pick random html element and style it

Hello I am need some help with javascript
I am newbie self-taught
How can i code - I have a table and 2 buttons, when i press button I want to pick random table data (from 1 to 9) and change it background color
and when i press second button - change table data from 1 to 9 in order.
// my javascript knowledge is very low but i understand that i need to
give id for my each table data,
a button with onclick="random()",
function random () - but i dont know how to pick random ID i gave for my td
<script type="text/javascript">
//function random() {
// var myArray = new Array("1", "2", "3", "4", "5", "6", "7", "8", "9");
// var x = Math.floor((Math.random() * 9) + 1);}
document.getElementById("random").onclick = function () {
document.getElementById("1").style.backgroundColor = "red";
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Javascript homework</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style type="text/css">
table {
border: 1px solid black;
}
th, td {
height: 150px;
width: 150px;
text-align: center;
color: black;
background-color: white;
font-size: 35px;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<table>
<tr>
<td id="1">1</td>
<td id="2">2</td>
<td id="3">3</td>
</tr>
<tr>
<td id="4">4</td>
<td id="5">5</td>
<td id="6">6</td>
</tr>
<tr>
<td id="7">7</td>
<td id="8">8</td>
<td id="9">9</td>
</tr>
</table>
<button id="random" type="button" onclick="random()">Random</button>
<button id="next" type="button" onclick="next()">Next</button>
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
Edited:
See comments inside js:
function random(){
//make a collection with all td elements
var items = document.getElementsByTagName("td");
for( i=0; i < items.length; i++ ){
//that delete old backgroundColor style
items[i].style.backgroundColor = '';
};
//choose a random id between 1 and 9
var random_id = Math.floor((Math.random()*9)+1);
//aply the red style color to this random element
document.getElementById(random_id).style.backgroundColor = "#ff0000";
};
<!DOCTYPE html>
<html>
<head>
<title>Javascript homework</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style type="text/css">
table {
border: 1px solid black;
}
th, td {
height: 50px;
width: 50px;
text-align: center;
color: black;
background-color: white;
font-size: 15px;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<table>
<tr>
<td id="1">1</td>
<td id="2">2</td>
<td id="3">3</td>
</tr>
<tr>
<td id="4">4</td>
<td id="5">5</td>
<td id="6">6</td>
</tr>
<tr>
<td id="7">7</td>
<td id="8">8</td>
<td id="9">9</td>
</tr>
</table>
<button id="random" type="button" onclick="random()">Random</button>
<button id="next" type="button" onclick="next()">Next</button>
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
Just return a random number between 1 and 9 (See random function). Use document.getElementById to select that element, and set it to red.
See below:
function random() {
return Math.floor((Math.random() * 9) + 1);
}
document.getElementById("random").onclick = function () {
document.getElementById(random()).style.backgroundColor = "red";
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript homework</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style type="text/css">
table {
border: 1px solid black;
}
th, td {
height: 50px;
width: 50px;
text-align: center;
color: black;
background-color: white;
font-size: 15px;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<table>
<tr>
<td id="1">1</td>
<td id="2">2</td>
<td id="3">3</td>
</tr>
<tr>
<td id="4">4</td>
<td id="5">5</td>
<td id="6">6</td>
</tr>
<tr>
<td id="7">7</td>
<td id="8">8</td>
<td id="9">9</td>
</tr>
</table>
<button id="random" type="button" onclick="random()">Random</button>
<button id="next" type="button" onclick="next()">Next</button>
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>

JavaScript boolean if statement problems

I have a button that, when clicked, makes an alert window pop up. When the button is clicked, a variable called "master" changes from false to true. Then, I have an if statement that checks if the variable is true. If it is, then it alerts the value of the variable. Here's the problem: the last part isn't happening. It's like the if statement isn't executing, then it stops the rest of the program. I did check to see if the "master" variable is registering as true, and it is, so I don't really know what's wrong.
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style type="text/css">
#buttons{
margin-top: 50px;
}
#x{
margin-left: 10px;
}
#table{
margin-top: 15px;
background: gray;
table-layout: fixed;
width: auto;
width: 250px;
height: 250px;
}
</style>
</head>
<body>
<div class="container" id="buttons">
<h2 id = "h2" >Choose your team!</h2>
<button onclick = "myFunctions()" type = "button" class="btn btn-default"><span style = "font-weight: bold; font-size: 110%;">O</span></button>
<button type = "button" id = "x" class="btn btn-default"><span class = "glyphicon glyphicon-remove"></span></button>
<table id = "table" class="table table-bordered">
<tbody>
<tr>
<td id = "td" onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var master = false;
var servant = false;
function myFunction(){
alert('hi');
}
function myFunctions(){
master = true;
}
if (master == true) {
alert(master);
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
Refer the corrected code below.
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style type="text/css">
#buttons{
margin-top: 50px;
}
#x{
margin-left: 10px;
}
#table{
margin-top: 15px;
background: gray;
table-layout: fixed;
width: auto;
width: 250px;
height: 250px;
}
</style>
</head>
<body>
<div class="container" id="buttons">
<h2 id = "h2" >Choose your team!</h2>
<button onclick = "myFunctions()" type = "button" class="btn btn-default"><span style = "font-weight: bold; font-size: 110%;">O</span></button>
<button type = "button" id = "x" class="btn btn-default"><span class = "glyphicon glyphicon-remove"></span></button>
<table id = "table" class="table table-bordered">
<tbody>
<tr>
<td id = "td" onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
<tr>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
<td onclick="myFunction()"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var master = false;
var servant = false;
function myFunction(){
alert('hi');
master = true;
if (master == true) {
alert(master);
}
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
Reason is was not executing is you had function called as myFunctions but actually you were calling myFunction() for onclick event
First you set master to false, then you declare two functions: 'myFunction' and 'myFunctions', then you check if master == true. As master is false, so you won't see the alert.
When you click the buttons, only the function myFunction or myFunctions gets executed. The test 'master == true' does not get executed again, it is not part of the functions

Categories

Resources