I am trying to create a dashboard for our office, and I want to show the occupancy of the meeting rooms (we, unfortunately, do not have a proper meeting room system). I have some sensors which can spit out a CSV of whether the motion is detected or not and I have a plan of the office with the green or red overlays for each room.
Where I am stuck is in how to toggle the visibility of green or blue in the dashboard based on the CSV values. I.e. if the last value is "MotionDetected", show red, if the value is not "MotionDetected" then show green.
I'm very new to any coding, so I only have basic knowledge. Any help would be much appreciated!
Thanks in advance!
The expected output is if the last value in the CSV is "MotionDetected", show red, if the value is not "MotionDetected" then show green.
Get last value of csv: Get last part of CSV string
JavaScript:
var myCSV = "red,yellow,green,blue";
var csv_Data = myCSV.split(',');
var last = csv_Data[csv_Data.length - 1];
// or
//var last = myCSV.substr(myCSV.lastIndexOf(',') + 1);
// get the thing that changes color.
var ele = document.getElementById("theThingThatChangesColor");
if(last === "MotionDetected") {
ele.style.backgroundColor = "red";
} else {
ele.style.backgroundColor = "green";
}
If you have the classes you need inside a css file, you can change the class instead of the style: JS Change class of element
Based on wazz's generous help, and with some additional input from Alan Stines on Youtube for extracting the CSV string, I used the following code to make the above work!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="CSV Parsing css.css" type="text/css" rel="stylesheet">
<title>CSV Parsing Test</title>
</head>
<body>
<div id="output"></div>
<img id="Background" src="Brochure QR Code.png" alt="Broken">
<img id="TestImage" src="search.png" alt="Broken">
<script>
function init(){
var myCSV = new XMLHttpRequest();
myCSV.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var csv_Data = this.responseText.split(',');
console.log(csv_Data);
var last = csv_Data[csv_Data.length - 3];
console.log(last);
var ele = document.getElementById("TestImage");
if(last === "DetectedMovement"){
ele.style.backgroundColor = "red";
} else {ele.style.backgroundColor = "green";
}
}
};
myCSV.open("GET", "MotionLog_PIRTempHum001Testing R00.01.csv", true);
myCSV.send()
}
window.onload = init;
</script>
</body>
</html>
I hope sharing this helps!
Related
I'm making a program where it has a collection of calculators, and for some reason when I try to change the innerhtml of a certain text it only changes it during the if statement and not during the else part.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
GiveAnswer.innerHTML = `Processing...`;
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
};
https://replit.com/#ButterDoesFly/Arcane-Calculators#index.html
I'm not sure but I guess the reason for this is that the function never goes to the else part because it gets break every time. Remember that .reverse() reverses the array in place so the if statement will always be true. Try to add different variable for the reversed answer.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
GiveAnswer.innerHTML = `Processing...`;
setTimeout(()=>{
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
},1000)
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="PalindromeAnswer">This will tell you the number its at and then the answer.</p>
<input type="text" id="PalindromeInput" placeholder="What number would you like to enter?">
<br>
<input type="button" onclick="Palindrome()" value="Submit" id="PalindromeButton">
<script src="script.js"></script>
<!--
This script places a badge on your repl's full-browser view back to your repl's cover
page. Try various colors for the theme: dark, light, red, orange, yellow, lime, green,
teal, blue, blurple, magenta, pink!
-->
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
</body>
</html>
result is rendering very fast such that changes are not reflecting in ui..add a timeout so that changes reflect in front end
I have a problem with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<title>The Ultimate Quiz Challenge</title>
</head>
<body>
<div class="container">
<h1>The Ultimate Quiz Challenge</h1>
<script>
document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
var question1 ="<p>What is the capital of England</p>";
var firstanswer ="London";
var question2 = "<p>How many sides are there to a square</p>";
var secondanswer = 4;
var noofquestions = 2;
var count = 1
/*var temp = eval('question' +1); */
/*document.write(temp);*/
/* main loop asking questions */
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
</script>
</div>
</body>
</html>
When I load the file into a browser such a chrome or safari it does not execute as hoped.
In short the document.write commands do not come out onto the screen until the prompt window as asked for two inputs. I thought the first thing to be seen would be the Ultimate Quiz Challenge followed by the commands in the open script tag down to the bottom ?
You should use the onload event on your body, so your script executes once the html page is rendered. It should work with :
<body onload="displayText()">
displayText() being a function you define in your script :
var displayText = function () {
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
};
or something similar.
Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>
I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>
I'm trying to use Google's Images API to search an image and put it into my html document as a div. This is what I have so far, but nothing seems to be appearing. This is parts from http://code.google.com/apis/imagesearch/v1/devguide.html. This is my first time using an API, so I'm not sure what is really going on.
<html>
<head>
<title>Art Project FTW</title>
</head>
<body>
<br>
<br>
<form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
</form>
<script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
<script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('h2');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
}
}
function onload() {
// Our ImageSearch instance.
var imageSearch = new google.search.ImageSearch();
// Restrict to extra large images only
imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
google.search.ImageSearch.IMAGESIZE_MEDIUM);
// Here we set a callback so that anytime a search is executed, it will call
// the searchComplete function and pass it our ImageSearch searcher.
// When a search completes, our ImageSearch object is automatically
// populated with the results.
imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);
</script>
</body>
</html>
Thanks in advance!
It can't work because you are looking for a HTMLElement that has the ID='content', you haven´t anyone element with that ID
Try putting your js functions within <head></head>