Having trouble with onclick displaying and hiding differnt text - javascript

I have a table where the text in column on the left can be clicked and the text in the column on the right will change accordingly. The way it should work is when one of the options on the left is clicked, only the text on the right that corresponds to the selected option appears. However, when I click one of my options on the left it just hides all of the text on the right and does not display the part I want to see.
var selectColor = function( element ) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName( "prot_id" );
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
element.style.color = 'red';
}
}
var selectProtein = function( element ) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName( "prot_func" ) ;
for( j = 0; j < proteinInfo.length; ++j ) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
proteinIDs.forEach(function(entry) {
if( element.src.includes(entry)) {
var theProtein = document.getElementById(entry) ;
theProtein.style['display'] = 'block' ;
}
})
}
<head>
<link rel='stylesheet' type='text/css' href='./index.css'>
</head>
<body>
<table>
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
<p id="gria2" class="prot_func">...</p>
<p id="gria3" class="prot_func">...</p>
<p id="gria4" class="prot_func">...</p>
</td>
</tr>
</table>
</body>

There are a few issues that you are having so I updated your code.
I got rid of onclick and went with an event handler instead.
I got rid of the protein array loop and just added each id as a data attribute to the paragraph tags.
Instead of hiding/showing based on the style, I just add/remove a class instead.
var selectColor = function(element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for (i = 0; i < prots.length; ++i) {
prots.item(i).classList.remove("active");
}
element.classList.add("active")
}
var selectProtein = function(element) {
var proteinInfo = document.getElementsByClassName("prot_func");
for (j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].classList.remove("active");
}
theProtein = document.querySelector("#" + element.dataset.id);
theProtein.classList.add("active");
}
document.querySelectorAll(".prot_id").forEach(function(el) {
el.addEventListener("click", function(e) {
selectColor(e.target);
selectProtein(e.target)
});
});
.prot_func {
display: none;
}
.prot_func.active {
display: block;
}
.prot_id.active {
color: red;
}
<table>
<tr>
<td>
<p class="prot_id" data-id="gria1">GRIA1_HUMAN</p>
<p class="prot_id" data-id="gria2">GRIA2_HUMAN</p>
<p class="prot_id" data-id="gria3">GRIA3_HUMAN</p>
<p class="prot_id" data-id="gria4">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">.1..</p>
<p id="gria2" class="prot_func">.2..</p>
<p id="gria3" class="prot_func">.3..</p>
<p id="gria4" class="prot_func">..4.</p>
</td>
</tr>
</table>

From your snippet, you are going to show the options on the right side based on the selected p tag content.
So if GRIA1_HUMAN is selected, gria1 should be shown.
You can get the value of p content using innerText attribute and compare the values using it. I have attached the working example.
var selectColor = function (element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
}
element.style.color = 'red';
}
var selectProtein = function (element) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName("prot_func") ;
for( j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
const elementText = element.innerText.toLowerCase();
proteinIDs.forEach(function(entry) {
if(elementText.includes(entry)) {
var theProtein = document.getElementById(entry);
theProtein.style['display'] = 'block';
}
});
}
<table border="1">
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
</td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p></td>
<td><p id="gria2" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p></td>
<td><p id="gria3" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p></td>
<td><p id="gria4" class="prot_func">...</p></td>
</tr>
</table>

Related

Add columns to a new table row in JQuery

I have the following html:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
<td id=col4">7</td>
</tr>
</tbody>
</table>
I would like to use JQuery to append everything after column 3 (col3) to a new row. Ideally I would end up with something like this:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
</tr>
<tr>
<td id=col4">7</td>
</tr>
</tbody>
</table>
Any ideas how this could be achieved? I have tried a few things but haven't been able to get it working.
You could define a generic redistribution function, that takes as argument the desired number of columns, and which just fills up the rows with content from top to bottom, using that number of columns.
It could even be a jQuery plugin:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; border: 2px solid }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
Here is a version with one extra statement that sets the colspan on the very last td element so it occupies the remaining columns in the last row:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
$("td", this).last().attr("colspan", rowCount * maxNumCols - cells.length + 1);
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
It sounds like you're still new to jQuery. To give you an idea how to solve your described problem, I have written a solution here. I hope it helps you.
// parameters for splitting
var splitIndex = 3,
splitClass = '.split-columns';
// start the splitting
splitColumnsIntoRows();
function splitColumnsIntoRows() {
var $tables = $(splitClass),
numberTables = $tables.length;
if (numberTables == 0) {
return;
}
for (var i = 0; i < numberTables; i++) {
iterateSplittingRows($($tables[i]).find('tr'));
}
}
function iterateSplittingRows($currentRows) {
var $currentRow,
numberRows = $currentRows.length;
if (numberRows == 0) {
return;
}
for (var i = 0; i < numberRows; i++) {
$currentRow = $($currentRows[i]);
iterateSplittingFields($currentRow, $currentRow.find('th, td'));
}
}
function iterateSplittingFields($currentRow, $currentFields) {
var $newRow,
newRows = [],
childrenLength,
numberFields = $currentFields.length;
if (numberFields == 0) {
return;
}
for (var i = 0; i < numberFields; i++) {
if (i < splitIndex) {
continue;
}
if (i % splitIndex == 0) {
$newRow = $('<tr></tr>');
}
$newRow.append($currentFields[i]);
if (i == numberFields - 1) {
childrenLength = $newRow.children().length;
// fill the row with empty fields if the length does not fit the splitIndex
for (var j = splitIndex; j > childrenLength; j--) {
$newRow.append($('<td></td>'));
}
}
if (
(i >= splitIndex && i % splitIndex == splitIndex - 1)
||
i == numberFields - 1
){
newRows.push($newRow);
}
}
$currentRow.after(newRows);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="split-columns">
<tbody>
<tr>
<td class="col_01">01</td>
<td class="col_02">02</td>
<td class="col_03">03</td>
<td class="col_04">04</td>
<td class="col_05">05</td>
<td class="col_06">06</td>
<td class="col_07">07</td>
<td class="col_08">08</td>
<td class="col_09">09</td>
</tr>
<tr>
<td class="col_10">10</td>
<td class="col_11">11</td>
<td class="col_12">12</td>
<td class="col_13">13</td>
<td class="col_14">14</td>
<td class="col_15">15</td>
<td class="col_16">16</td>
<td class="col_17">17</td>
</tr>
<tr>
<td class="col_19">19</td>
<td class="col_20">20</td>
<td class="col_21">21</td>
<td class="col_22">22</td>
<td class="col_23">23</td>
<td class="col_24">24</td>
<td class="col_25">25</td>
</tr>
</tbody>
</table>

Show calculated arithmetic mean in <td> when the button is clicked

please help me finish this, I'm getting nowhere.
what needs to be done
final results
I've explained in the pictures whats the finish goal.
This is a grade calculator.
There are 3 types of grades.. it should calculate the arithmetic mean for every category and arithmetic mean for all grades no matter which category they are.
Calculated values should be shown on the appropriate block, as shown in the picture.
input[type="number"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="number"]:focus{
outline : none;
}
</style>
<body>
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Add grade</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick=""> Calculate </button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Written test</td>
<td style="width:70px; text-align: center;">Essay</td>
<td style="width:70px; text-align: center;">Class Activity</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all Writtentest, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all Essay, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all ClassActivity, inside td-->
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Arithmetic mean of all grades</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all numbers-->
</tr>
</tbody>
</table>
</div>
</body>
<script>
var ocena = 0;
var stranica = document.querySelector("#stranica")
function removeElement(obrisi) {
var dugme = obrisi.target;
stranica.removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max",5);
input.setAttribute("min",1);
var myParent = document.body;
//Create array of options to be added
var array = ["Written test","Essay","Class Activity"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
stranica.appendChild(item)
}
</script>```
var ocena = 0;
function removeElement(obrisi) {
var dugme = obrisi.target;
document.getElementById("stranica").removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max", 5);
input.setAttribute("min", 1);
var myParent = document.body;
//Create array of options to be added
var array = ["Kontrolni", "Vezbe", "Aktivnost"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
document.getElementById("stranica").appendChild(item)
}
function calcMean() {
var nameList=document.querySelectorAll('#stranica .item #mySelect');
var inputList=document.querySelectorAll('#stranica .item input');
var kontrolniList = [];
var vezbeList = [];
var aktivnostList = [];
var ocenaList = [];
for(var i=0; i< nameList.length; i++){
ocenaList.push(parseInt(inputList[i].value));
if(nameList[i].value=='Kontrolni') {
kontrolniList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Vezbe') {
vezbeList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Aktivnost') {
aktivnostList.push(parseInt(inputList[i].value));
}
}
document.getElementById("kontrolni").innerHTML=avg(kontrolniList);
document.getElementById("vezbe").innerHTML=avg(vezbeList);
document.getElementById("aktivnost").innerHTML=avg(aktivnostList);
document.getElementById("ocena").innerHTML=avg(ocenaList);
}
function avg( arr ) {
var total = 0, i;
for (i = 0; i < arr.length; i += 1) {
total += arr[i];
}
return total / arr.length;
}
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Dodaj ocenu</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick="javascript:calcMean();"> Izracunaj prosek</button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Kontrolni</td>
<td style="width:70px; text-align: center;">Vezbe</td>
<td style="width:70px; text-align: center;">Aktivnost</td>
</tr>
<tr>
<td id="kontrolni" style="text-align: center;"> </td>
<td id="vezbe" style="text-align: center;"></td>
<td id="aktivnost" style="text-align: center;"></td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Zakljucna ocena</td>
</tr>
<tr>
<td id="ocena" style="text-align: center;"> </td>
</tr>
</tbody>
</table>
</div>
Hope this will work.

How to change name of cloned radio button in javascript only

I am trying to change the name of cloned radio button (which are creating dynamically) so that these radio buttons can be select from all . Current only one radio button can be selected.
Please find below the HTML
<table class="ebTable" style="border-left:1px solid #e6e6e6;border-right:1px solid #e6e6e6;">
<thead>
<tr>
<th>{{fieldName}}</th>
<th>{{fieldType}}</th>
<th>{{mandatory}}</th>
<th>
<button class="ebBtn" e-id="start" name="start">
<i class="ebIcon ebIcon_add"></i>
<span>Add</span>
</button>
</th>
</tr>
</thead>
<tbody>
<tr id="repeat">
<td>
<e-forminput type="text" e-id="fieldName" />
</td>
<td>
<e-forminput type="select" value="{{selectType}}" items="IA5String" e-id="fieldType" />
</td>
<td>
<e-forminput type="radio" e-id="mandatory" name="mandatory" options="true:{{yes}},false:{{no}}" />
</td>
<td>Delete Button</td>
</tr>
</tbody>
</table>
Please find below the JavaScript code
onViewReady: function() {
var i = 0;
this.view.findById("start").addEventHandler("click", function() {
var original = document.getElementById('repeat');
var clone = original.cloneNode(true); // for clone
clone.id = "repeat" + ++i; // there can only be one element with an ID
var size = document.getElementsByName("mandatory").length;
console.log(size);
for (var j = 0; j < size; j++) {
if (clone.childNodes[j].nodeName.toLowerCase() == 'input' && clone.childNodes[j].nodeType == 'radio') {
clone.childNodes[j].name = "mandatory" + i;
}
}
original.parentNode.appendChild(clone);
}.bind(this));
}

jQuery disable click function when value gets to 0

I've been trying many different methods and rewriting my code to achieve something that I feel is quite simple but I can't seem to get it.
I have two increment/decrement buttons but I want to disable the click function on the subtract button when the value reaches 0 as to not input negative numbers.
Currently on my jsfiddle I have the calculator working, however when I try to disable the subtract button when the value is 0, it disables the button completely, even when the value is no longer 0. It seems jQuery is not checking to see if the value has changed.
Any ideas on how can I fix this? Thanks!
Example here:
https://jsfiddle.net/jony000/frupofqe/22/
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
JQuery
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function() {
showers++;
rate.html(showers);
})
minus.click(function() {
showers--;
rate.html(showers);
})
/*if (showers == 0) {
minus.css("pointer-events","none");
} else{
minus.css("pointer-events", "auto");
}*/
You have to check if shower is zero inside the click event listener for the minus element:
minus.click(function() {
rate.html(--showers);
if (showers === 0) {
minus.css("pointer-events", "none");
} else{
minus.css("pointer-events", "auto");
}
});
Check for 0 before you decrement. I believe its more clearly readable to just not decrement it rather than disabling the control, unless you had other logic thats not shown in the demo.
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function(){
showers++;
rate.html(showers);
})
minus.click(function(){
if (showers <= 0)
return;
showers--;
rate.html(showers);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
you just need to move your entire if block at the bottom inside of your functions... or better yet, create a new function and call that one inside the others. Here's an example
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
//This is new
var checkForZero = function() {
if (showers == 0) {
minus.css("pointer-events","none");
} else {
minus.css("pointer-events", "auto");
}
};
plus.click(function(){
showers++;
rate.html(showers);
checkForZero(); //call new function
})
minus.click(function(){
showers--;
rate.html(showers);
checkForZero(); //call new function
})
you can do something like this.
var rateMinus = $(".rate-minus");
var value = 0;
updateRateMinus(); // update on initial load
$(".rate-plus").click(function() {
parseInt($(".shower-rate").text(value + 1));
value = value + 1;
updateRateMinus();
});
$(".rate-minus").click(function() {
parseInt($(".shower-rate").text(value - 1));
value = value - 1;
updateRateMinus();
});
function updateRateMinus() {
if ($(".shower-rate").text() == 0) {
rateMinus.css('pointer-events', 'none');
} else {
rateMinus.css("pointer-events", "auto");
}
}
You could just set up an call that would check a given condition (if your value is 0) and use that to toggle if your subtract button was enabled or disabled via a ternary operation :
minus.css("pointer-events",showers === 0 ? "none" : "auto");
Then you could simply check for that scenario when either of your events occur :
plus.click(function(){
showers++;
UpdateRate();
})
minus.click(function(){
showers--;
UpdateRate();
})
function UpdateRate() {
// This will disable your button if showers is 0
minus.css("pointer-events",showers === 0 ? "none" : "auto");
rate.html(showers);
}
Example
var rateMinus = $(".rate-minus");
var ratePlus = $(".rate-plus");
var rate = $(".shower-rate");
var value = 0;
ratePlus.click(function() {
value++;
UpdateRate();
})
rateMinus.click(function() {
value--;
UpdateRate();
})
function UpdateRate() {
debugger;
// This will disable your button if showers is 0
rateMinus.css("pointer-events", value === 0 ? "none" : "auto");
rate.html(value);
}
table {
margin: auto;
color: #cecece;
}
.shower td {
padding: 10px;
}
.rate-minus,
.rate-plus,
.period-minus,
.period-plus {
width: 50px;
height: 50px;
background: #a8d6ff;
border-radius: 100%;
text-align: center;
font-size: 24px;
color: black;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How often do you shower?
<table class="shower">
<tbody>
<tr>
<td class="rate-minus" id="test">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a
</p>
<table class="shower">
<tbody>
<tr>
<td class="period-minus">
-
</td>
<td class="shower-period">
Day
</td>
<td class="period-plus">
+
</td>
</tr>
</tbody>
</table>

Javascript get id from element and then use it

Can you help me with this problem? I can't use return x value for my other function. I want when I click on some element, then script load ID of clicked element and then change color of element with this ID.
Is there some better solution for my problem? (in pure JS, not in Jquery)
Thanks.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
<script>
document.addEventListener('click', function(e) {
x=e.target.id;
return x
});
document.getElementById(x).onclick =
function(x) {
if (document.getElementById(x).style.backgroundColor !== 'yellow') {
document.getElementById(x).style.backgroundColor = 'yellow';
}
else {
document.getElementById(x).style.backgroundColor = 'red';
}
};
</script>
Change your code to below.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
document.addEventListener('click', function(e) {
x=e.target.id;
function() {
var bgColor = document.getElementById(x).style.backgroundColor;
if (bgColor !== 'yellow') {
bgColor = 'yellow';
}
else {
bgColor = 'red';
}
}
});
</script>
Ok i find solution on my problem.
The solution was put all my script in one function and than evrything work.
I learning JS about 1 mount and now I have made one simple LIGHTS OFF game.
Now I nedd some function that check all cells color and alert end of game, but i cant answer a new question because by question is not voted well, and i dont know why.
Here is the example of my code:
document.addEventListener('click', function(e) {
var x = e.target.id
var up = ((Math.floor(x.charAt(0))-1).toString()).concat(x.charAt(1));
var down = ((Math.floor(x.charAt(0))+1).toString()).concat(x.charAt(1));
var left = (x.charAt(0)).concat((Math.floor(x.charAt(1))-1).toString());
var right = (x.charAt(0)).concat((Math.floor(x.charAt(1))+1).toString());
if( document.getElementById(x).style.backgroundColor == ''){document.getElementById(x).style.backgroundColor = 'black';}
else{document.getElementById(x).style.backgroundColor ='';}
if(document.getElementById(up)!=null){
if( document.getElementById(up).style.backgroundColor == ''){document.getElementById(up).style.backgroundColor = 'black';}
else{document.getElementById(up).style.backgroundColor ='';}}
if(document.getElementById(down)!=null){
if( document.getElementById(down).style.backgroundColor == ''){document.getElementById(down).style.backgroundColor = 'black';}
else{document.getElementById(down).style.backgroundColor ='';}}
if(document.getElementById(left)!=null){
if( document.getElementById(left).style.backgroundColor == ''){document.getElementById(left).style.backgroundColor = 'black';}
else{document.getElementById(left).style.backgroundColor ='';}}
if(document.getElementById(right)!=null){
if( document.getElementById(right).style.backgroundColor == ''){document.getElementById(right).style.backgroundColor = 'black';}
else{document.getElementById(right).style.backgroundColor ='';}}
// var all = document.getElementsByTagName("TD");
// var i;
// for (i = 0; i < all.length; i++) {
// all[i].style.backgroundColor!=='yellow';
// alert('a')
// break}
})
td {
padding: 50px;
background-color: yellow;
<table>
<tr>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
</tr>
<tr>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
</tr>
<tr>
<td id='31'></td>
<td id='32'></td>
<td id='33'></td>
<td id='34'></td>
<td id='35'></td>
</tr>
<tr>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
</tr>
<tr>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
</tr>
</table>

Categories