Random Color for <tr> - javascript

So overall I am trying to make the boxes change color when someone puts a mouse over them. Color has to be random. I know I am missing a connection point between my functions but I cant figure out what it is.
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'
onmouseenter = "colorize();"
>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
Create a function called colorize that is passed an element object as its
parameter and sets the elements background color style property using the
rgb(r,g,b) method setting each r,g and b to a random number between 0 and
255.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function colorize(co) {
document.body.style.background = co;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
Use document.write() and for-loops to fill in the table to create a 16x16 box table. For each td element, create a onmouseenter call to colorize, passing it the element itself (this).
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>

I'm not sure what you wanted to do with body background, nothing said about that in your text. ALos your colorizer func is overwritten. maybe you wanted something like this... ?
<!DOCTYPE html>
<html>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
function colorize(el) {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
el.style.backgroundColor = '#' +r+g+b;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td onMouseEnter='colorize(this);'></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>

You need to have your colorize function update each cell in your table. Replace both colorize() and colorize(co) with one function:
function colorize() {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
for (var i = 0; i < document.getElementsByTagName("td").length; i++){
document.getElementsByTagName("td")[i].style.backgroundColor = "#"+r+g+b;
}
}

i play with Ids and adding onmousedown in html tag that calls the func.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function change(){
var x = document.getElementById("1");
var y = document.getElementById("2");
x.style.color = colorize();
y.style.color = colorize();
}
<table frame="box" onmousedown="change()"id="1" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
<table frame="box" onmousedown="change()" id="2" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>February</td>
<td>$200</td>
</tr>
</table>

Related

Store draggable DIV's position in HTML Table to MySQL database

I'd like to know if/how i will be able to store the position of where I move a draggable div to on the table, so when the page is reloaded, it will return to were it was left (from MySQL database).
i read some articles about that but it was all about using jquery (event, ui) with AJAX.
here's my code :
var p = document.getElementsByTagName('p');
var choice = document.getElementsByClassName('choice');
var dragItem = null;
for(var i of p){
i.addEventListener('dragstart', dragStart);
i.addEventListener('dragend', dragEnd);
}
function dragStart(){
dragItem = this;
setTimeout(()=>this.style.display = "none", 0);
}
function dragEnd(){
setTimeout(()=>this.style.display = "block", 0);
dragItem = null;
}
for(j of choice){
j.addEventListener('dragover', dragOver);
j.addEventListener('dragenter', dragEnter);
j.addEventListener('dragleave', dragLeave);
j.addEventListener('drop', Drop);
}
function Drop(){
this.append(dragItem);
}
function dragOver(e){
e.preventDefault();
this.style.border = "2px dotted cyan";
}
function dragEnter(e){
e.preventDefault();
}
function dragLeave(e){
this.style.border = "none";
}
section{
width: 1000px;
height: 360px;
margin: 100px auto;
display: flex;
justify-content: space-around;
}
h1{
text-align: center;
}
div{
width: 200px;
height: 90%;
padding: 20px;
margin: 10px;
background: #fafafa;
box-sizing: border-box;
}
p{
font-weight: bold;
border-radius: 5px;
padding: 5px;
color: white;
background: red;
}
table, th, td {
border:1px solid black;
}
button{
width: 100px;
height: 15px;
padding: 15px;
margin: 10px;
background: gray;
box-sizing: border-box;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test drag & drop </title>
</head>
<body>
<h1> it's just a test for js </h1>
<section>
<div2>
<table style="width:100%">
<tr>
<th>time</th>
<th>DIM</th>
<th>LUN</th>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td><div class="choice"></div> S1-1</td>
<td><div class="choice"></div>S1-2</td>
</tr>
<tr>
<td>9:00 - 10:00</td>
<td><div class="choice"></div>S2-1</td>
<td><div class="choice"></div>S2-2</td>
</tr>
</table>
<button>save</button>
</div2>
<div class="choice">
<p draggable="true">MODULE 1</p>
<p draggable="true">MODULE 2</p>
<p draggable="true">MODULE 3</p>
<p draggable="true">MODULE 4</p>
<p draggable="true">MODULE 5</p>
</div>
</section>
</body>
</html>
This may be an overcomplicated answer. But I feel the best way to go about this is to store an array of module objects inside your javascript. Each module would have a position attribute that would need to be updated every time a module is moved. You could also use the data html attribute to store the position of the element on the element itself(https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). Here is my code:
Javascript:
var dragItem = null;
let modules = loadDataFromServer();
//Initial UI
updateUI(modules);
function dragStart() {
console.log("Start")
dragItem = this;
setTimeout(() => this.style.display = "none", 0);
}
function dragEnd() {
console.log("End")
setTimeout(() => this.style.display = "block", 0);
dragItem = null;
}
function Drop() {
console.log("Drop")
console.log(dragItem)
this.append(dragItem);
moveModuleTo(modules.length - 1, modules[dragItem.dataset.position])
}
function dragOver(e) {
e.preventDefault();
this.style.border = "2px dotted cyan";
}
function dragEnter(e) {
e.preventDefault();
}
function dragLeave(e) {
this.style.border = "none";
}
//Added Code
function loadDataFromServer() {
//return an array of modules
return [
{
title: "Module 1",
position: 0
},
{
title: "Module 2",
position: 1
},
{
title: "Module 3",
position: 2
},
{
title: "Module 4",
position: 3
},
{
title: "Module 5",
position: 4
},
]
}
function moveModuleTo(position, module) {
if (module.position < position) {
//Module is moving down the list
console.log(position)
console.log(module.position)
for (let i = module.position; i < position; i++) {
modules[i] = modules[i + 1];
modules[i].position = i
}
} else {
//Module is moving up the list
for (let i = module.position - 1; i > position; i--) {
modules[i] = modules[i - 1]
modules[i].position = i + 1;
}
}
modules[position] = module
modules[position].position = position
console.log(modules)
//Update UI and database
updateUI(modules)
}
function updateUI(modules) {
let choice = document.getElementsByClassName('choice');
//Remove old Modules
const draggableContainer = document.getElementById("draggableContainer")
while (draggableContainer.firstChild) {
draggableContainer.removeChild(draggableContainer.lastChild)
}
//Add updated Modules
modules.forEach(item => {
console.log("yeet")
let newDraggableItem = document.createElement('p')
newDraggableItem.innerHTML = `${item.title}`
newDraggableItem.draggable = true
newDraggableItem.dataset.position = item.position
draggableContainer.appendChild(newDraggableItem);
});
//ReAdd Event listeners
var p = document.getElementsByTagName('p');
for (var i of p) {
i.addEventListener('dragstart', dragStart);
i.addEventListener('dragend', dragEnd);
}
for (j of choice) {
j.addEventListener('dragover', dragOver);
j.addEventListener('dragenter', dragEnter);
j.addEventListener('dragleave', dragLeave);
j.addEventListener('drop', Drop);
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<title>test drag & drop </title>
</head>
<body>
<h1> it's just a test for js </h1>
<section>
<div2>
<table style="width:100%">
<tr>
<th>time</th>
<th>DIM</th>
<th>LUN</th>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td>
<div class="choice"></div> S1-1
</td>
<td>
<div class="choice"></div>S1-2
</td>
</tr>
<tr>
<td>9:00 - 10:00</td>
<td>
<div class="choice"></div>S2-1
</td>
<td>
<div class="choice"></div>S2-2
</td>
</tr>
</table>
<button>save</button>
</div2>
<div class="choice" id="draggableContainer"></div>
</section>
<script src="app.js"></script>
</body>
</html>
For updating a database you could make a write database call every time you move a module. Then every time the page is loaded just sort the array based on the position value. Hope this helps!

JavaScript updating only after 2-3 seconds?

I have a HTML table where I wanted to introduce sorting and search options and therefore I used Jquery which has JS & CSS file
The table is giving the correct output but whenever the page is loaded, first the table is updating without above js and css and only after 2-3 seconds, the above Jquery is updated. How can I make it fast so that it does not awkward for the user ?
Here is the HTML Code
{% load function %}
<!-- <link rel='stylesheet' href='media/css/jquery.dataTables.min.css'> -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link rel='stylesheet' href='https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css'>
<script>$(document).ready(function () {
$('#example').DataTable();
});</script>
<table id='example' class='table'>
<thead>
<tr>
<th>Stock</th>
<th>Open</th>
<th>High</th>
<th>Low</th>
<th>Close</th>
<th>Volume</th>
<th>Buyers</th>
<th>Sellers</th>
<th>Close_open</th>
<th>Close_high</th>
<th>high_open</th>
<th>high_low</th>
</tr>
</thead>
<tbody id="people">
{% for x,y in info.items %}
<tr>
<td scope="row">{{x|split}}</td>
<td id= 'open{{x}}'>{{y|access_dictionary:'ohlc'|access_dictionary:'open'}}</td>
<td id='high{{x}}'>{{y|access_dictionary:'ohlc'|access_dictionary:'high'}}</td>
<td id='low{{x}}'>{{y|access_dictionary:'ohlc'|access_dictionary:'low'}}</td>
<td id='close{{x}}'>{{y|access_dictionary:'ohlc'|access_dictionary:'close'}}</td>
<td>{{y|access_dictionary:'volume'}}</td>
<td id='buyquantity{{x}}'>{{y|access_dictionary:'buy_quantity'}}</td>
<td id='sellquantity{{x}}'>{{y|access_dictionary:'sell_quantity'}}</td>
<td id='Close_open{{x}}'></td>
<td id='Close_high{{x}}'></td>
<td id='high_open{{x}}'></td>
<td id='high_low{{x}}'></td>
<script>
// console.log(document.getElementById('high{{x}}').innerHTML)
// console.log(document.getElementById('low{{x}}').innerHTML)
// console.log(document.getElementById('open{{x}}').innerHTML)
d = document.getElementById('close{{x}}').innerHTML - document.getElementById('open{{x}}').innerHTML
e = document.getElementById('close{{x}}').innerHTML - document.getElementById('high{{x}}').innerHTML
f = document.getElementById('high{{x}}').innerHTML - document.getElementById('open{{x}}').innerHTML
g = document.getElementById('high{{x}}').innerHTML - document.getElementById('low{{x}}').innerHTML
document.getElementById('Close_open{{x}}').innerHTML = Math.round(d * 100)/100;
document.getElementById('Close_high{{x}}').innerHTML = Math.round(e * 100)/100;
document.getElementById('high_open{{x}}').innerHTML = Math.round(f * 100)/100;
document.getElementById('high_low{{x}}').innerHTML = Math.round(g * 100)/100;
</script>
</tr>
{% endfor %}
</tbody>
</table>
<!-- <script>
setTimeout(function(){
window.location.reload(1);
},2000);
</script> -->
<style type="text/css">
table {
border-collapse: collapse;
border: none;
width: 20%;
}
th,
td {
border: 1px solid black;
padding: 2px 8px;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
text-align: left;
}
th {
background-color: #C8C8C8;
cursor: pointer;
width:100px;
}
</style>
Here {% for x,y in info.items %} info is the dictionary where all stock related information is stored. Therefore I have run a loop to display it on a webpage. Please reply
Try updating the file if (linked):
<script id="update" src="yourfile.js"></script>
<script>
for (var i = 0; i < 2; i++) {
var e = '';
if (i == 1) {
e = '?random=1234';
} else {
e = '?random=123456';
}
window.update.src += e;
}
</script>
Or if the file is an absolute url,like "http://www.example.com" and your url is different, try putting the file in your directory. Try setting cache if it is disabled on your page because then it can get the file easier.

Save content editable HTML table in multiple fields

I need to develop a HTML table where one of the table column is editable on its row and the table row is dynamic in term of the row number.
I come across a problem where when I automate the saveEdits() function, the code is not working.
Here is my code, where the 'cnt' is a dynamic numeric number. Example cnt=50
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
table ,tr td{
border:1px solid #dddddd;
padding: 8px;
}
tbody {
display:block;
height:600px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
thead {
width: calc( 100% - 1em )
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script type="text/javascript">
function saveEdits(cnt) {
//get the editable elements.
var str_out = ''
while (cnt>0){
str1 = '\'edit' + cnt + '\': document.getElementById(\'edit' + cnt + '\').innerHTML,\n'
str_out = str_out.concat(' ', str1);
cnt--;
};
var editElems= { str_out };
alert(editElems)
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
function checkEdits(){
//find out if the user has previously saved edits
var userEdits = localStorage.getItem('userEdits');
alert(userEdits) // suppose to print {"edit1":" rpeyy7<br>","edit2":" tpruiiy<br>","edit3":" opty<br>"}
if(userEdits){
userEdits = JSON.parse(userEdits);
for(var elementId in userEdits){
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
</script>
</head>
<body onload="checkEdits()">
<table id="myTable">
<thead>
<tr>
<td style="background-color:#A9A9A9" > Field#1 </td>
<td style="background-color:#A9A9A9" > Field#2 </td>
<td style="background-color:#A9A9A9" > Field#3- Each Row Under field#3 is content EditableByUser </td>
</tr>
</thead>
<tbody>
// Here is the python code that loop through a diectionary content
cnt = 0
for c in sorted(data_dict.keys()) :
cnt += 1
<tr>
<td> {0} </td> //Field#1
<td> {0} </td> //Field#2
...
...
<td id="edit{0}" contenteditable="true" onKeyUp="saveEdits({0});"> {1} </td>\n'.format(cnt,comment)]
</tr>
</table>
</body>
I'm not sure where goes wrong as when I automate the saveEdits() function with 'cnt' in while loop, the above code doesn't works for me. But when I defined each row clearly like below, the data the keyed-in are properly saved to each column.
function saveEdits(cnt) {
//get the editable elements.
var editElems = {
'edit1': document.getElementById('edit1').innerHTML,
'edit2': document.getElementById('edit2').innerHTML,
'edit3': document.getElementById('edit3').innerHTML,
};
alert(editElems) //print [object Object]
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
I would be much appreciate if someone can point out my mistake. The error is very much likely on saveEdits(cnt) function but I'm not sure how to fix that cause it I define each count 1 by 1, each update that being keyed-in is actually saved properly and able to retrieve when rerun. Thanks you!

auto refrsh api data

i need to refresh particular data line in every interval when the value change
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()+ randomnumber);
}, 1000);
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
document.getElementById('output').innerHTML=data;
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="output" style="margin:5px 0;">
</div>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</body></html>
Here i get all refreshed in every seconds. i need to refresh only a particular line
Hi Here I done as per your req, Just one line I have done, for other line do by your self, I just makes your string obj into obj and added table style.
js fiddle
html
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<div id="output" style="margin:5px 0;">
</div>
<table>
<tr>
<th style="margin-left:20px">exchange</th>
<th>fromSymbol</th>
<th>toSymbol</th>
<th> volume24h</th>
<th>volume24hTo</th>
</tr>
<tr>
<td>Bitfinex</td>
<td>BTC</td>
<td>USD</td>
<td id="volume24h">BTC</td>
<td id="volume24hTo">USD</td>
</tr>
</table>
java script
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()) + randomnumber;
}, 1000);
gettxt()
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
var dataTemp = JSON.parse(data);
document.getElementById('volume24h').innerHTML=dataTemp.Data[0].volume24h;
document.getElementById('volume24hTo').innerHTML=dataTemp.Data[0].volume24hTo;
console.log(dataTemp);
})
}

How to add data to table on click of button using Javascript

<html>
<head>
<style type="text/css">
table, th, td {
position: relative;
border: 1px solid black;
width: 40%;
height:40px;
top: 5%;
}
</style>
<script type="text/javascript">
function lab()
{
var x= document.getElementById('lab').value;
var rows="";
rows+= "<tr><td>"+x+"</td></tr>";
}
function inp()
{
var y= document.getElementById('inp1').value;
}
</script>
</head>
<body>
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td></td>
<td></td>
</tr>
<tbody></tbody>
</table>
</html>
I am trying to add the text in the column of the table on the click of the button.
so please help me to add the text written on the button in the column of the table
thank you
I don't understand your requirement completely, but you can use innerHTML to wipe out earlier contents and insert new. Or use appendChild and createElement to make and insert new elements on the go. The example demonstrates both with each button.
function lab() {
var x = document.getElementById('lab').value;
var rows = "";
rows += "<tbody><tr><td>" + x + "</td></tr></tbody>";
document.getElementById('me1').innerHTML = rows;
}
function inp() {
var table = document.getElementById('me1');
var tbody = table.getElementsByTagName('tbody')[0];
var y = document.getElementById('inp1').value;
var text = document.createTextNode(y);
var col = document.createElement('td');
var row = document.createElement('tr');
col.appendChild(text);
row.appendChild(col);
tbody.appendChild(row);
}
table,
th,
td {
position: relative;
border: 1px solid black;
width: 40%;
height: 40px;
top: 5%;
}
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td></td>
<td></td>
</tr>
<tbody></tbody>
</table>
I have been also trying out how to input values into HTML table with the click of a button, and I found out this simple way by just using innerHTML and the id of the td tag. I have reformatted your code, hope this would be useful.
<!DOCTYPE html>
<head>
<style type="text/css">
table, th, td {
position: relative;
border: 1px solid black;
width: 40%;
height:40px;
top: 5%;
}
</style>
<script type="text/javascript">
function lab()
{
var x= document.getElementById('lab').value;
document.getElementById('00').innerHTML=x;
}
function inp()
{
var y= document.getElementById('inp1').value;
document.getElementById('01').innerHTML=y;
}
</script>
</head>
<body>
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td id='00'></td>
<td id='01'></td>
</tr>
<tbody></tbody>
</table>
</html>

Categories