A simple JavaScript not working - javascript

I want to measure the time in which the user keeps the site on focus, but it doesn't work.
<!doctype html>
<head>
<script>
var timeActive;
function timeActiveFuncStart(){
timeActive = 0;
function timeActiveFunc(){
timeActive++;
setTimeout("timeActiveFunc()", 1000)}}
var timeActiveTotal;
function timeActiveTotalFunc(){
timeActiveTotal = timeActiveTotal + timeActive}
document.getElementById("timeActiveP").innerHTML = timeActive;
document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
</script>
</head>
<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">
<p id="timeActiveP"></p>
<p id="timeActiveTotalP"></p>
</body>
</html>

It is because, JavaScript cannot access the elements. And also, consider using setInterval instead of setTimeout this way:
Please replace the <script> to go to the bottom:
<!doctype html>
<head>
</head>
<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">
<p id="timeActiveP"></p>
<p id="timeActiveTotalP"></p>
<script>
var timeActive;
var timeActiveTotal = 0;
function timeActiveTotalFunc() {
timeActiveTotal = timeActiveTotal + timeActive;
}
function timeActiveFuncStart() {
timeActive = 0;
function timeActiveFunc() {
timeActive++;
document.getElementById("timeActiveP").innerHTML = timeActive;
document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
}
setInterval(timeActiveFunc, 1000);
}
</script>
</body>
</html>
Or, can you put it after window.onload event?
<!doctype html>
<head>
<script>
window.onload = function () {
var timeActive;
function timeActiveFuncStart(){
timeActive = 0;
function timeActiveFunc(){
timeActive++;
}
setInterval("timeActiveFunc()", 1000);
var timeActiveTotal;
function timeActiveTotalFunc(){
timeActiveTotal = timeActiveTotal + timeActive}
document.getElementById("timeActiveP").innerHTML = timeActive;
document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
}
</script>
</head>
<body onfocus="timeActiveFuncStart()" onblur="timeActiveTotalFunc()">
<p id="timeActiveP"></p>
<p id="timeActiveTotalP"></p>
</body>
</html>

Thanks again for the help, but ... here's something that finally works:
<script>
var timeActive = 0;
var timeActiveTotal = 0;
window.onpageshow = function(){
setInterval(function(){
timeActive++;
document.getElementById("timeActiveP").innerHTML = timeActive;
}, 1000);
window.onblur = function(){
timeActiveTotal = timeActiveTotal + timeActive;
document.getElementById("timeActiveTotalP").innerHTML = timeActiveTotal;
}
window.onfocus = function(){
timeActive = 0;
}
}
</script>

Related

Hide AND unhide a <div> or <form> while executing code (progress bar a.o.)

the goal is to hide a form, do some stuff and unhide the form again. For example with this code for a progress bar I thought to do the following but the hiding/unhiding doesn't work. I'm probably overseeing something obvious.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
show_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function(){update()},10);
show_div();
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
var x = document.getElementById("do_you_see_me?");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}//end function
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
you can hide and unhide it. the problem with your code is when you trigger ready buton it will hide and then unhide the code automatically. this is becuase setInterval() function is asynchronious function. then you need call show_div() function inside the setInterval().
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
hide_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function()
{
update()
if(count>=countmax)
{
show_div();
}
},10);
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
document.getElementById("do_you_see_me?").style.display="block";
}//end function
function hide_div()
{
document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
i hope this will fix your problem.

.innerHTML with setTimeout prints only the last part in loop

I am new to JavaScript.
What I want to do is print the elements of an array one by one on the same location, but after a specific time interval.
Here it prints only the last element.
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<script>
const words = [ "Word1" , "word2" , "word3" , "word4" ];
for (let i = 0; i < words.length; i++ ) {
console.log(words[i]);
setTimeout(function(){ document.getElementById('test').innerHTML = words[i]; }, 2000);
}
</script>
</body>
</html>
You can try this,it prints all one after the other
const words = ["Word1", "word2", "word3", "word4"];
for (let i = 0; i < words.length; i++) {
console.log(words[i]);
setTimeout(function() {
document.getElementById('test').innerHTML += words[i];
document.getElementById('test2').innerHTML = words[i];
}, 2000 * i);
}
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<p id="test2"></p>
</body>
</html>
You are using the wrong function.
A timeout just pauses the script for a period of time, what you are looking for is setInterval.
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<script>
const words = ['Word1', 'word2', 'word3', 'word4'];
i = 0;
const counter = setInterval(foo, 1000);
function foo() {
document.getElementById('test').innerHTML = words[i];
i++;
if (i >= 4) clearInterval(counter);
}
</script>
</body>
</html>

Webcam Image Update in Javascript

I am having major brain ache on this one. I have a webcam that i snap an image from every 5 seconds. I have read all of the comments and I can successfully display an image from the webcam but cannot get the image to update. I have read the similar posts and tried everything.
Am i missing something?
This is what I have:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Webcam</title>
<script type="text/javascript">
var x = 0;
function init() {
window.onmessage = (event) => {
if (event.data) {
var ImageURL = document.getElementById("webcam1");
ImageURL.src = event.data;
Clear();
function Clear() {
document.getElementById("Load").style.display = "None";
document.getElementById("Test").innerHTML = "Clearing";
setInterval(UpdateImage, 20000);
function UpdateImage() {
x = x + 1;
var temp = ImageURL.src;
UpdatedImageURL.src = temp + "?=t" + new Date().getTime();
var UpdatedImageURL = document.getElementById("webcam1");
document.getElementById("Test").innerHTML =
"Updating .... " + x;
}
}
}
}
}
</script>
</head>
<body onload="init();">
<p id="Load">Loading ....</p>
<p id="Test">Starting ....</p>
<img id="webcam1" alt=" " width="700" height="450" />
</body>
</html>

How to add the returned value from a JavaScript function into an HTML element [duplicate]

I am looking for a way to call a javascript number in the body of an html page. This does not have to be long and extravagant just simply work, I just want something like:
<html>
<head>
<script type="text/javscript">
var number = 123;
</script>
</head>
<body>
<h1>"the value for number is: " + number</h1>
</body>
</html>
Try This...
<html>
<head>
<script>
function myFunction() {
var number = "123";
document.getElementById("myText").innerHTML = number;
}
</script>
</head>
<body onload="myFunction()">
<h1>"The value for number is: " <span id="myText"></span></h1>
</body>
</html>
Use document.write().
<html>
<head>
<script type="text/javascript">
var number = 123;
</script>
</head>
<body>
<h1>
the value for number is:
<script type="text/javascript">
document.write(number)
</script>
</h1>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write but
can't avoid <script> tag
<script type="text/javascript">
function get_param(param) {
var search = window.location.search.substring(1);
var compareKeyValuePair = function(pair) {
var key_value = pair.split('=');
var decodedKey = decodeURIComponent(key_value[0]);
var decodedValue = decodeURIComponent(key_value[1]);
if(decodedKey == param) return decodedValue;
return null;
};
var comparisonResult = null;
if(search.indexOf('&') > -1) {
var params = search.split('&');
for(var i = 0; i < params.length; i++) {
comparisonResult = compareKeyValuePair(params[i]);
if(comparisonResult !== null) {
break;
}
}
} else {
comparisonResult = compareKeyValuePair(search);
}
return comparisonResult;
}
var parcelNumber = get_param('parcelNumber'); //abc
var registryId = get_param('registryId'); //abc
var registrySectionId = get_param('registrySectionId'); //abc
var apartmentNumber = get_param('apartmentNumber'); //abc
</script>
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">
document.write(registrySectionId)
</script></td>
Here is another way it can be done .
function showData(m)
{
let x ="<div> added from js ";
let y = m.toString();
let z = "</div>";
let htmlData = x+y+z ;
content.insertAdjacentHTML("beforeend",htmlData);
}
You can do the same on document ready event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);.
<?php
$x1='<span id="x1"></span><script>document.getElementById("x1").innerHTML = x1;</script>';
$x2='<span id="x2"></span><script>document.getElementById("x2").innerHTML = x2;</script>';
$x3='<span id="x3"</span><script>document.getElementById("x3").innerHTML = x3;</script>';
?>
<html><body>
<script> var
x1="123",
x2="ABC",
x3=666;
</script>
<?php echo $x1 ?><br>
<?php echo $x2 ?><be>
<?php echo $x3 ?><be>
</body></html>
Index.html:
<html>
<body>
Javascript Version: <b id="version"></b>
<script src="app.js"></script>
</body>
</html>
app.js:
var ver="1.1";
document.getElementById("version").innerHTML = ver;
You cannot add JavaScript variable to HTML code.
For this you need to do in following way.
<html>
<head>
<script type="text/javscript">
var number = 123;
document.addEventListener('DOMContentLoaded', function() {
document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

events javascript

I need to display a message on mouse click. But I also need another message to be displayed on the next mouse click. The problem is that in my code both messages appear on the first mouse click.
<!DOCTYPE>
<html>
<head>
<script>
function myfunction()
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
if(obj.innerHTML=="message1")
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>
<script>
var flag=0;
function myfunction()
{
if (flag==0)
{
var obj=document.getElementById("msg1");
obj.innerHTML="message1";
flag=1;}
else
{
var obj1=document.getElementById("msg2");
obj1.innerHTML="message2";
}
}
</script>
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
obj1.innerHTML = "message2";
}else{
obj.innerHTML = "message1";
}
Your if would always execute because you were trying to check if obj.innerHTML == "message1" immediately after setting it to that.
Do you see that you set the innerhtml of obj to "message1" and then immediately after you check if the innerHTML is "message1" that will always be true.
You need to change the if. So it says:
if(obj.innterHTML=="message1"){
obj.innerHTML="message2";
} else {
obj.innerHTML="message1";
}
Similar to others, but what the heck:
var obj1 = document.getElementById('msg1');
var obj2 = document.getElementById('msg2');
if (obj1.innerHTML == '') {
obj1.innerHTML = 'message1';
} else {
obj2.innerHTML = 'message2';
}
function myfunction() {
var i, ele;
for(i = 1; i <= 2; i++) {
ele = document.getElementById("msg"+i);
if (ele && ele.innerHTML.length == 0) {
ele.innerHTML = 'message' + i;
return;
}
}
}
Just add a click counter to check it was first click or more then first.
<!DOCTYPE>
<html>
<head>
<script>
var $clickCount = 0;
function myfunction() {
$clickCount++;
var obj = document.getElementById("msg1");
obj.innerHTML = "message1";
if (obj.innerHTML == "message1") {
var obj1 = document.getElementById("msg2");
if ($clickCount == 2) {
obj1.innerHTML = "message2";
}
}
}
</script>
</head>
<body>
<div id="msg">
<form name="myform">
<input type="button" value="click" onclick="myfunction()">
<p id="msg1"></p>
<p id="msg2"></p>
</form>
</div>
</body>
</html>

Categories