I'm trying to run a function at pageload:
<script type="text/javascript" src="functions.js"></script>
<body onload="startUp();">
The problem is startUp() isn't running, nor is anything else that I try to refer to in my JS file. I am certain that the link to the JS file is correct; and even if it weren't, I even tried pasting all of functions.js right into the page header--still nothing. This is the content of functions.js:
function startUp() {
document.write("running"); //for debugging
alert("running"); //for debugging
stretchAbdomen();
if (defaultStyle()) {
setStyleCookie(1, false);
}
else { //if mobilestyle
setStyleCookie(0, false);
if (!window.location.hash) {
window.location.hash = "#mobilearea";
}
}
}
function stretchAbdomen() {
var bodyheight = getbodyheight();
var abdomen = document.getElementById('abdomen');
if (window.innerHeight > bodyheight) {
var currentpaddingstring = window.getComputedStyle(abdomen, null).getPropertyValue('padding-bottom');
var currentpadding = Number(currentpaddingstring.substring(0, currentpaddingstring.length - 2)); //-2 removes "px" from string
abdomen.style.paddingBottom = (((window.innerHeight - bodyheight) + currentpadding) + "px";
}
}
function getbodyheight() {
var body = document.body,
html = document.documentElement;
return Math.min( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
}
/*** BELOW HERE SHOULD NOT BE RELEVANT FOR THE QUESTION ***/
window.onresize = resetStyleCookie;
function defaultStyle() {
if (window.getComputedStyle(document.getElementById('mobilearea')).getPropertyValue('width') == "1px")
return true;
else return false;
}
function resetStyleCookie() {
document.cookie = "stylecookie=" + "; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
setStyleCookie(defaultStyle() ? 1 : 0, true); //forcereset because otherwise it wasn't working on subpages
}
function setStyleCookie(number, forcereset) {
if (document.cookie.indexOf("stylecookie") == -1 || forcereset) {
var now = new Date();
var time = now.getTime();
time += 3600 * 150000;
now.setTime(time);
document.cookie = "stylecookie=" + number + "; expires=" + now.toGMTString() + "; path=/";
}
}
I have to assume that there's some compile-time problem in functions.js, but my debugging tools show no errors, nor can I find anything myself. The call to startUp() simply does nothing, even when I don't rely on the onload event to call it. Thanks for any insight!
You have an error in your JS code. Try using JSLint.com to validate your code.
if (window.innerHeight > bodyheight) {
var currentpaddingstring = window.getComputedStyle(abdomen, null).getPropertyValue('padding-bottom');
var currentpadding = Number(currentpaddingstring.substring(0, currentpaddingstring.length - 2)); //-2 removes "px" from string
abdomen.style.paddingBottom = (((window.innerHeight - bodyheight) + currentpadding) + "px";
}
You are missing the last ) on abdomen.style.padding.bottom.
Error: Expected ')' to match '(' from line 22 and instead saw ';'.
<html>
<head>
<script type="text/javascript">
function startUp() {
document.write("running"); //for debugging
alert("running"); //for debugging
//stretchAbdomen();
if (defaultStyle()) {
setStyleCookie(1, false);
}
else { //if mobilestyle
setStyleCookie(0, false);
if (!window.location.hash) {
window.location.hash = "#mobilearea";
}
}
}
</script>
</head>
<body onload="startUp();">
</body>
</html>
The above code works for me. As you can see, I've taken only the function you are trying to reference and have put it in script tags -- but it works. It seems to me that the problem occurs when you try to reference the stretchAbdomen function.
You need to reference the function, f.e.
<body onload="startUp">
Make sure to reference it after it was defined (as you did in your example with the external JavaScript).
Related
My son is doing times tables practice on this page, a timed test in which he gets 10 seconds for each sum.
https://www.timestables.com/speed-test/ - this is not my site or code, I have no direct control over the source code.
I want to give him a little more time per sum but I cannot find a way to modify the relevant code and make it work with 20 seconds instead of 10.
It looks to me like the relevant variable is maxTime (milliseconds) in this function, but nothing I do using the Chrome Developer Tools will modify this in a live running page to give 20 seconds instead of 10.
function startSom(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 10000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Can anyone suggest what to do please?
You can copy the entire method, pase it into chrome devtools and change
function startSom() {
to
window.startSom = function() {
And obviously change your time from 10000 to 20000. This changes the amount of time it allows you to answer, but not the moving progress bar which will still only take 10 seconds.
Please paste this:
window.startSom = function(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 20000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Here:
And if you want to make the progress bar following the new max Time, also paste this:
window.animateUpdate = function() {
if(bezig)
{
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
if(!started){
$('#pbar_innerdiv').css("width", (100) + "%");
$('#pbar_innerdiv').animate({width: 0 + "%"},20000);
started = true;
}
perc = Math.round((timeDiff/maxTime)*100);
console.log(perc);
if(perc == 33)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF9500");
$('#pbar_innerdiv').css("borderColor", "#FF9500");
}
if(perc== 66)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF0000");
$('#pbar_innerdiv').css("borderColor", "#FF0000");
}
if (perc <= 100) {
//updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
else
{
bezig = false;
showTeLaat();
//alert("tijd is om");
}
}
}
There is a possibility to change files persistently in chrome devtools: Overrides.
If the script is in a seperate file you can change the maxTime directly there or if it is in a file, which needs to be reloaded you can edit any other .js and add an eventlistener there to change the startSom method on page load.
In a jsf web application based on Seam and Richfaces, I ran into a problem concerning different browsers. The code (and every variation I tried) works flawless in Chrome, but not in Internet Explorer (I am testing version 11).
The code is supposed to start and display a session-timeout countdown in the header. In the beginning of the template file, the timeout is retrieved from the application preferences and stored in a hidden field. The countdown timer is reset whenever a new page is loaded, or when an AJAX request is triggered (resetInactivityTimer()).
I am having 2 problems in IE:
It seems that the window.onloadfunction is not triggered on IE. The counter starts working fine when triggered manually in the console.
When the counter is started manually, an error occurs when an AJAX request is triggered.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
<link rel="shortcut icon" type="image/x-icon" href="#{facesContext.externalContext.requestContextPath}/img/favicon.ico" />
<a:loadStyle src="/stylesheet/theme.css" />
<ui:insert name="head" />
</head>
<body>
<h:inputHidden id="originalTimeoutId" value="#{preferencesManager.getPreferenceValue(Preference.HTTP_SESSION_TIMEOUT)}"/>
<a:loadScript src="/scripts/script.js"/>
<a:region id="status_zone">
<a:status for="status_zone" forceId="false" id="ajaxStatus" onstart="resetInactivityTimer()">
<f:facet name="start">
<h:panelGroup>
<div style="position: absolute; left: 50%; top: 50%; text-align:center; width: 100%; margin-left: -50%;z-index: 10001;" >
<h:graphicImage value="/img/wait.gif"/>
</div>
<rich:spacer width="95%" height="95%" style="position: absolute; z-index: 10000; cusor: wait;" />
</h:panelGroup>
</f:facet>
</a:status>
<div class="main">
<ui:include src="/layout/header.xhtml" />
<ui:include src="/layout/menu.xhtml" />
<div style="margin-top: 10px;">
<ui:insert name="body" />
</div>
<ui:include src="/layout/footer.xhtml" />
</div>
</a:region>
<script type="text/javascript">
window.onload = initCountdown();
</script>
</body>
</html>
The countdown timer is displayed in the top right corner in the Header file "header.xhtml", which is loaded in the template, and therefore contained on every page:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<div class="header">
<s:graphicImage value="#{preferencesManager.getPreferenceByteContent(Preference.LOGO)}" styleClass="logo"/>
<h:panelGrid width="92%" columns="3" columnClasses="headerCol2,headerCol3,headerCol4">
<h:outputText styleClass="titel"
value="#{cM.getStringProp('de.gai_netconsult.kodaba.text.title')}"/>
<span class="timer">Automatischer Logout in: </span>
<h:outputText id="counter" styleClass="timer"></h:outputText>
</h:panelGrid>
</div>
The time is placed at the id="counter" position.
This is the Javascript code: "script.js"
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
var initialized = false;
function initCountdown(){
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
startCountdown();
}
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function resetInactivityTimer() {
if (initialized) {
console.log("resetInactivityTimer - initialized: " + initialized);
stopCountdown();
countdown(timeoutInSeconds, 'counter');
}
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
initialized = true;
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function stopCountdown() {
var element = document.getElementById('counter');
clearTimeout(element.timerId);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function calculateAndShow(target) {
var element = document.getElementById('counter');
if (element.seconds >= 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,target);
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML=
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
element.seconds--;
} else {
completed(target);
return false;
}
}
function completed(target) {
var element = document.getElementById(target);
element.innerHTML = "<strong>Finished!<\/strong>";
}
Some things I tried is replacing
<script type="text/javascript">
window.onload = initCountdown();
</script>
with
<script type="text/javascript">
if (window.attachEvent) {window.attachEvent('onload', initCountdown());}
else if (window.addEventListener) {window.addEventListener('load', initCountdown(), false);}
else {document.addEventListener('load', initCountdown(), false);}
</script>
This leads to a "Typeconflict".
or with:
<rich:jQuery name="jcountdown" query="initCountdown()" timing="onload"/>
None of this helps.
I was able to get my timer to work in the end and I will post my solution here:
Problem 1:
<script type="text/javascript">
jQuery(document).ready(function(){
startCountdown();
});
</script>
instead of window.onload = startCountdown(); solves the problem.
Important: when using any console.log() statements, the function will only be executed when the developer console is opened! (F12).
Problem 2: (AJAX)
Richfaces version 3.3 is simply not compatible with any Internet Explorer Version above IE8.
It is important to apply a patch. This site describes the process in detail.
I also had to make many changes to the Javascript code. I am sure this could be much more elegantly written, but I confess I don't really know much Javascript at all... I'm posting my code anyway, in case somebody may find it useful:
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60 -1;
timeoutInSeconds;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function resetCountdown(){
var element = document.getElementById('counter');
element.seconds = timeoutInSeconds;
updateDisplay(element);
}
function calculateAndShow() {
var element = document.getElementById('counter');
if (element.seconds > 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,'counter');
updateDisplay(element);
element.seconds--;
} else {
completed();
return false;
}
}
function updateDisplay(element){
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML =
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function completed() {
var element = document.getElementById('counter');
element.innerHTML = "<strong>Beendet!<\/strong>";
logoutCallBackToServer();
}
Somewhere in one of your xhtml files (template, Header, menu, whatever) you also need to add this line:
<a4j:jsFunction name="logoutCallBackToServer" immediate="true" action="#{identity.logout}" />
This will ensure that the user is actually logged out precisely when the countdown reaches zero, just in case this does not 100% match the actual session time out.
I'm having trouble running a JS code from separate stylesheet on HTML page. Basically, I want to set an adequate greeting messages depending on the current hour of the day. I've searched and there are many ways to do it, but I am trying to get it work in this way and I didn't find a solution to this problem.
window.onload = getGreeting();
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} if else (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobar dan!";
} if else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
};
<!DOCTYPE html>
<head>
<script type="text/javascript" src="LakaRukaDent.js"></script>
</head>
<body>
<p id="greeting"></p>
</body>
When I run the HTML in Chrome the greeting doesn't appear. When I press f12 in Chrome it comes up with "Uncaught SyntaxError: Unexpected token <", but I can't figure out why it doesn't work. I've checked syntax and functionality searching through the web but considering that I'm new with JS and HTML perhaps it could be some basic thing that I've skipped and I am not aware of.
Use else if instead of if else.
Example from MDN:
if (x > 5) {
} else if (x > 50) {
} else {
}
Please find the fix below. window.onload expects a function reference not returned value of a function, that is why i remove parenthesis over there. Also there was syntax error with if else statement.
window.onload = getGreeting;
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} else if (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobar dan!";
} else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
};
<h1 id="greeting"></h1>
First off, remove the parentheses from getGreeting when assigning to onload, as onload accepts a function. Also, you have syntax errors with your if statements. It should be else if not if else like so:
window.onload = getGreeting;
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} else if (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobro dan!";
} else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
}
<p id="greeting"></p>
I want to make a little 'loading...' widget for my website, using javascript.
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setTimeout("count",50)
document.write(message)
document.write(percent)
document.write(per)
}
But it isn't running. I think I've got some mistake (or maybe totally wrong). How can I do this? I want to update the shown message every 50ms.
try with interval and clear it when progress is finished:
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="progress">MSG</div>
<script type="text/javascript">
var percent = 0;
var message = "Loading... ";
var per = "%";
var dom = document.getElementById('progress');
var iv = setInterval(function(){
console.log(message);
dom.innerHTML = ((percent++) + per +' '+ message);
if(percent === 100){
console.log("Loading end.");
clearInterval(iv);
return false;
}
}, 50);
</script>
</body>
</html>
try
setInterval(count,50);
instead of setTimeOut("count",50)
You want to set an interval which runs every x milliseconds, passing in an anonymous function to call the function to call
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setInterval(function() { count() },50)
document.write(message)
document.write(percent)
document.write(per)
}
} <--- you were also missing this ending brace
Script:
var percent = 0;
var message = "Loading... ";
var per = "%";
$(document).ready(function () {
count();
});
function count() {
percent = percent + 1;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(function () {
count();
}, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
see this fiddle for more http://jsfiddle.net/8nhmU/19/
See this jsfiddle
HTML:
<span id="loading"></span>
Javascript:
var percent = 0;
var message = "Loading...";
var per = "%";
var element = document.getElementById('loading');
var interval = setInterval(function() {
element.innerHTML = message + percent + per;
percent += 1;
if(percent > 100) {
clearInterval(interval)
};
}, 50)
The code in your example is missing a great deal of semi-colons and the ending curly-bracket, but that's not the end-issue.
The "problem" with your call to setTimeout is that the first argument must be an actual function, not a string. If you remove the quotes around the call, it will work.
Here is a copy of your code, re-formatted:
var percent=0;
var message="Loading... ";
var per="%";
function count() {
percent++;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(count, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
You are doing it wrong way. You should call the setInterval method when window loads. And when loading is completed, you should stop interval by clearing it using its ID.
var countId;
window.onload = function(){
countId=setInterval(count,50);
}
function count(){
if(per=99){
clearInterval(countId);
}
per++;
//show your message
}
I'm trying to get a one-time alert when a user visits a website, then place a cookie so they're not annoyed with it every time they come back to the site. The cookie is saved and the alert executing, but it KEEPS executing and I'm tearing my hair out.
I've tried a number of things found on the web (StackExchange, how I love thee) but none seem to work. Here's the current state:
<script>
function setCookie(name, value, days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+days*24*60*60*1000);
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name+"=" + value+expires + ";path=/";
}
</script>
<body>
<script type="text/javascript">
if(!setCookie('testcookie')) {
alert("hello world");
setCookie('testcookie','1',3);
}
</script>
</body>
Looking at the cookie records, it seems to be setting every time. If I change the expiration date in the script, it changes in the dev console every time. Not sure if that's indicative of the problem or not.
===== END SOLUTION ======
I was missing the getCookie call. I also realized that when trying to add it to the header scripts, the execution needed to be it's own function * facepalm *. I also added all the scripts to the header and instead call the function in the body tag.
<head>
<script>
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+days*24*60*60*1000);
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name+"=" + value+expires + ";path=/";
}
var getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
function checkCookie() {
if(!getCookie('testcookie2')) {
alert("hello world");
setCookie('testcookie2','1',3);
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
TA-DA!
I use a little javascript function sometimes to retrieve cookies
var getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
you can use this in conjunction with your other logic
if(!getCookie('testcookie')) {
alert("hello world");
setCookie('testcookie','1',3);
}