Having trouble getting my HTML onload to call my JS function - javascript

I have a function that should be called whenever my html page loads. The <body> tag should call the startAdPage() function. However, nothing at all happens. I am not completely sure why. Any suggestions? Here is the <body> call in my HTML page
<body onload="startAdPage();">
Next, here is my startAdPage() function, as well as the two functions it calls. Those two aren't completely finished yet. One of them is supposed to create a small image gallery slide show. The other is supposed to create a countdown from 10 - 1 before displaying a separate web page. Neither work yet, so any advice on them would also be appreciated, though they aren't my main focus yet.
function startAdPage(){
setInterval(changeAd(), 2000);
setInterval(startCountdown(), 1000);
}
Here is changeAd()
function changeAd() {
for(var i = 1; i < 4; i++){
document.images[0].src = "images/pic" + intNumber + ".jpg";
}
}
Lastly, startCountdown(). I haven't made the webpage that I said this function calls yet
function startCountdown() {
window.alert('Test');
for(var i = 10; i >= 1; i++){
document.getElementById("countdown").value = i;
}
}

Your problem is right here:
document.images[0].src = "images/pic" + intNumber + ".jpg";
You refer to intNumber but you should be using i instead. So change the above to
document.images[0].src = "images/pic" + i + ".jpg";
and your function will be called.
You should consider removing the onload in the body tag and do a
window.onload = startAdPage;
instead - to keep your html and Js logic separate.
Also, your countdown logic is wrong - you want to decrement i, not increment:
var i = 10; i>0; i--

Related

document.location enacted after subsequent code

Hello lovely people of StackOverflow.
I'm trying to create a dynamic page using JavaScript AJAX and PHP.
I have created a list of images which have unique ids numbers 1-12. When one is clicked it should pass that id onto a function which changes the page, then uses the id number to load in content to the new page.
My problem is that when I use document.location to change the page (or window.assign) it does not change the page before enacting the following code which loads in the content. Therefore it tries to load the content to a div which doesn't exist on the current page, then changes the page. Does anybody know why this is? And how I can solve it?
I have tried putting the document.location and innerHTML code in separate functions, but the next function is still called before the page changes. I have also tried putting an if statement ahead of the content load but that is also called before the page changes.
Here is my code:
function output (bookList){
for (var i = 0; i < titles.length; i++) {
document.getElementById("insertBooksHere").innerHTML += "<ul class=\"bookItem\">";
for (var t = 0; t<position.length; t++){
if (t==position.length-1)
{
x = bookList[i][0];
document.getElementById("insertBooksHere").innerHTML += "<img class=\'books\' id = \'" + x + "\' src=\'" +bookList[i][t]+ "\' onClick=\'getBookDetails("+ x +")\'>";
}
else
if ( t == 1 || t==2){
document.getElementById("insertBooksHere").innerHTML += "<li>"+bookList[i][t]+"</li>";
}
}
document.getElementById("insertBooksHere").innerHTML += "</ul></div>";
}
}
function getBookDetails(id){
bookID = id;
for ( var t = 0; t<12; t++)
{
bookDetails[t] = bookList[bookID-1][t];//grab details about specified book from array using x as the value for i.
}
loadBookPage(bookID, bookDetails)
}
function loadBookPage(bookID, bookDetails){
console.log(window.location.href);
}
function loadBookDetails(){
if ( document.location == 'books/'+bookID+'.php')
{
x = bookID;
console.log(bookDetails);
document.getElementById("book").innerHTML += "<ul class=\"bookItem\">";
for (var t = 0; t<position.length; t++){
if (t==position.length-1)
{
document.getElementById("book").innerHTML += "<img class=\'books\' id = \'" + x + "\' src=\'" +bookDetails[t]+ "\'>";
}
else {
document.getElementById("book").innerHTML += "<li>"+bookDetails[t]+"</li>";
console.log("for loop");
}
console.log(bookDetails[t]);
}
document.getElementById("book").innerHTML += "</ul>";
document.getElementById("book").innerHTML += "HELLO!!!";
}
}
And you can see my work here: http://itsuite.it.brighton.ac.uk/rlr17/bookClub/home.php
Thanks guys! Really appreciate your help.
My problem is that when I use document.location to change the page (or window.assign) it does not change the page before enacting the following code which loads in the content.
That is how JavaScript (when running client side, embedded in a webpage) works.
It runs in that page.
If the page goes away (because you loaded a new page) then its execution environment goes away and it stops running.
If you want to do something in the next page then you have to pass some data to that page and have code in the new page read that data and act on it.
Ideally, you would do this using server side code (as it is more reliable, and rarely has an additional runtime cost when you are loading a new page anyway).

Why is Javascript function not being called?

First Question on this site so I hope I do this right! I have a javascript function that I want to display an image (image1.jpg) when the page is loaded, and then every 2 seconds change the image by going through the loop. However only the first image is showing so it seems the JS function is not being called. Can anyone tell me if I am doing something wrong here because it looks fine to me so can't understand why it won't work. Thanks
<html>
<head>
<script type="text/javascript">
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var i = 1;
if(i>images.length-1){
this.src=images[0];
i=1;
}else{
this.src=images[i];
i++;
}
setTimeout("displayImages()", 2000);
}
</script>
</head>
<body onload="displayImages();">
<img id="myButton" src="image1.jpg" />
</body>
</html>
You need to move the line
var i = 1;
outside the displayImages -function or it will start from one each time!
EDIT: But using a global variable is not considered good practice, so you could use closures instead. Also as noted in other answers, you are referencing this which does not refer to the image object, so I corrected that as well as simplified the logic a bit:
<script type="text/javascript">
function displayImages( i ){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var img = document.getElementById('myButton');
img.src = images[i];
i = (i+1) % images.length;
setTimeout( function() { displayImages(i); }, 2000 );
}
</script>
<body onload="displayImages(0);">
You need the value of i to be available at each call, it can be kept in a closure using something like:
var displayImages = (function() {
var i = 0;
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
return function() {
document.getElementById('myButton').src = images[i++ % images.length];
setTimeout(displayImages, 2000);
}
}());
Also, since this isn't set by the call, it will default to the global/window object, so you need to get a reference to the image. That too could be held in a closure.
There are a couple of issues here that are stopping this from working.
First the var i = 1; needs to be moved outside the function to make the increment work. Also note that the first item in an array is 0, not 1.
Second you're using this to refer to change the image's src, but this is not a reference to the image. The best thing to do is use here is document.getElementById instead.
var i, button;
i = 0;
button = document.getElementById('myButton');
function displayImages() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if (i > images.length - 1){
button.src = images[0];
i = 0;
}
else{
button.src = images[i];
i++;
}
setTimeout(displayImages, 2000);
}
There's still some room for improvement and optimisation, but this should work.
You are reinitializing value of i every time, so change the following:
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(!displayImages.i || displayImages.i >= images.length) displayImages.i = 0;
document.getElementById('myButton').src = images[displayImages.i];
displayImages.i++;
setTimeout(displayImages, 2000);
}
Functions are objects in JS and because of this:
you can pass them by reference and not as a string improving performance and readability
you can add fields and even methods to a function object like I did with displayImages.i
EDIT: I've realized that there was one more issue src was not being set for button.
Now I've fixed this and also made other improvements.
Here is the fiddle http://jsfiddle.net/aD4Kj/3/ Only image URLs changed to actually show something.
<script type="text/javascript">
var i = 1;
function displayImages(){
.......
........
Just make "i" Global. so that whenever displayImages being called it will not redefined to 1.
<html>
<head>
<script type="text/javascript">
var i = 1;
function displayImages() {
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
i++;
if (i > images.length - 1) {
i = 0;
}
$('#myButton').attr('src', images[i]);
setTimeout(displayImages, 2000);
}
</script></head>
<body onload="displayImages();">
<img id="myButton" src="img1.jpg" height="150px" width="150px"/>
</body>
</html>
Make i global.
here your are using displayImages() recursively and variable for index i. e i assign as local variable in function displayImages() , you need to assign it global variable i.e outside of the function also initialize it from i=0 as array index always start from 0,
your code become
var i = 0; // assign i global
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(i>images.length-1){
document.getElementById('myButton').src=images[0]; //get img by id
i=0; // to get first image
}
else{
document.getElementById('myButton').src=images[i]; //get img by id
i++;
}
setTimeout("displayImages()", 2000);
}

Issue with setTimeOut and non-response script in IE8

I am getting an issue with a large amount of processing causing the non-responsive script error in IE8 (and no, I cannot make the users use a better browser).
I then read that it should be possible to split up the tasks and cede control back to the browser in between different parts of the validation. So I decided to make a simple example based on some code I found to figure out where the breaking points are. The real code is doing lots of jquery validationengine processing.
I tried to use jsFiddle but I can't get jsFiddle to run in IE8. Bummer. So, I'll have to share inline here.
When I first load it, it seems to work just fine. I push the button and both functions finish without a problem. However, subsequent pushes causes an unresponsive script error. I've played around with the number of loops in my simulated work function. Much more than 1.25 million loops and it dies with unresponsive script.
Shouldn't separate calls to the onClick start the non-responsive counter anew? What am I missing here?
<html>
<head>
<script>
var progress = null;
var goButton = null;
window.onload = function() {
progress = document.getElementById("progress");
goButton = document.getElementById("goButton");
}
function runLongScript(){
// clear status
progress.value = "";
goButton.disabled=true;
var tasks = [function1, function2];
multistep(tasks,null,function() {goButton.disabled=false;});
}
function function1() {
var result = 0;
var i = 1250000;
for (;i>0; i--) {
result = result + 1;
}
progress.value = progress.value + "f1 end ";
}
function function2() {
var result = 0;
var i = 1250000;
for (;i>0; i--) {
result = result + 1;
}
progress.value = progress.value + "f2 end";
}
function multistep(tasks, args, callback){
var tasksClone = tasks.slice(0); //clone the array
setTimeout(function(){
//execute the next task
var task = tasksClone.shift();
task.apply(null, args || []);
//determine if there's more
if (tasksClone.length > 0){
setTimeout(function () {
multistep(tasksClone, args, callback);
}, 100);
} else {
callback();
}
}, 100);
}
</script>
</head>
<body>
<p><input type="button" id="goButton" onClick="runLongScript();" value="Run Long Script" /></p>
<input type="text" id="progress" />
</body>
</html>
You're never calling clearTimeout() to remove the one currently running when the button has been pressed already. Add an if statement before you start another setTimeout and check to see if one is already running, clear it if it is, and then continue. Here's a link that should help you if you have any questions: https://developer.mozilla.org/en-US/docs/Web/API/window.clearTimeout

jQuery onclick() function within a for loop

This is probably a simple jQuery/js question but I'm a novice at this and could
use some help.
function launchResultViewer(){
var elen =$MP.data.REG_AS_RS.ASSIGNEE.length;
for (i = 0 ; i < elen ; i++)
{var dEventid = $MP.data.REG_AS_RS.ASSIGNEE[i].EVENT_ID;
var objPVViewerMPage = window.external.DiscernObjectFactory("PVVIEWERMPAGE"); objPVViewerMPage.CreateProcViewer(patientId);
objPVViewerMPage.AppendProcEvent(dEventid);
objPVViewerMPage.LaunchProcViewer(); } }
function OnClickForm(){
var xlen =$MP.data.REG_AS_RS.ASSIGNEE.length;
for (i = 0 ; i < xlen ; i++){
var dOrderid = $MP.data.REG_AS_RS.ASSIGNEE[i].ORDER_ID;
<a href='#'title ="+dOrderid+" onclick='javascript:launchResultViewer(\"" + dOrderid + "\");'>Order</a>"
$('#clickme').click(function(){ ,} }
Say there is two elements in "i" every time I click on the link two screens open up. Each link should only open up once, what am I missing in click function?
Any help would be great.
your first problem is writing your js inline. get rif of the onclick anchor, thats what the #click me event listener is for. in the click me function put what ever action you want it to do there, and get rid of all other anchors, your code is not totally full because you have an empty function at the bottom, but I can almost bet you are calling the same function twice.
change
Order
to order
( your going to have to css it to make it have anchor behavior)
<script>
$('#clickme').click(function(){
launchResultViewer(\"" + dOrderid + "\");
});
</script>

How to change the function called by a dynamically created button?

I was making a little game in JavaScript when I ran into a problem. In this game I create a hundred buttons using a for() loop. Eventually I want every button to call a function called 'click' and send it an int so it knows what button is pressed. So for instance when button four is pressed click(4) is called. First I tried this:
object.onclick = "click(4)";
That obviously didn't work so i searched the interwebs and fount an answer to this question on your site.
object.onclick = function() {click("4");}
I tried that (with and without the ';' at the end) but it doesn't seem work.
A more complete overview of the dummy code:
<script type="text/javascript">
document.getElementById('myContainer').innerHTML += '<input id="tmp" type="button" value="button">';
documengetElementById('tmp').onclick = function() {tmpFunc("bla");}
function tmpFunc(vari){
alert(vari);
}
</script>
The element myContainer is 100% empty!
Remember, this is just dummy code to try it out. I could do this waaaaay easier but I tried to simplify it first so you don't have to look at my messy code.
So what is the best way to call a function from a button you have created in a for loop? If you know a way to do it totally different from the one I use just post it, I don't care how it gets solved! Although I'd also like somebody to explain why this isn't working.
Hope I didn't ask a question already answered, as far as I know I'm using the solution given for this problem in another post.
------------UPDATE-------------
Changed it a bit after getting an answer from somebody. This is the current code, select() isn't executed when a button is pressed. Here's the complete JavaScript code so you can copy-paste it if you want to play around with it.
<script type="text/javascript">
function addButtons(){
var disabled = false;
for(var i = 1; i <= 100; i++){
currentButton = '<input id="tmp" type="button" onclick="select(\''+i+'\')">'
document.getElementById('myContainer').innerHTML += currentButton;
document.getElementById('tmp').id = 'btn'+i;
gb(i).disabled = disabled;
gb(i).style.width = "60px";
gb(i).style.height = "60px";
gb(i).style.fontSize = "25pt";
function alerts(nr){
alert("test");
}
if(i%10 == 0){
document.getElementById('myContainer').innerHTML = document.getElementById('myContainer').innerHTML + '<br />';
}else{
if(disabled){
disabled = false;
}else{
disabled = true;
}
}
if(i == 60){
gb(i).value = 'O';
gb(i).style.color = "blue";
}
if(((i-1)%10 == 0) && !(gb(i).disabled)){
gb(i).value = 'X';
gb(i).style.color = "red";
}
}
}
function select(nr){
alert("Bla!"+nr);
gb(nr).style.height = "100px";
}
function gb(ButtonNrVanHetButton){
return document.getElementById('btn'+ButtonNrVanHetButton);
}
addButtons();
</script>
Most parts aren't very interesting for solving the problem (style etc) It's supposed to look like a checkerboard.
------------UPDATE-------------
Solved! Don't use functions the javascript library already uses for other stuff like: 'select()'. Thx to everybody who tried to help!
If you are looping to create the buttons, why don't you add an onclick to the button?
for instance
<script>
// your function
function tmpFunc(vari)
{
alert(vari);
}
// end your function
// define xBUTTONS
xBUTTONS = '';
for (i=0; i<100; i++)
{
// loop buttons
xBUTTONS += '<input id="tmp" type="button" value="button" onclick="tmpFunc(\''+i+'\')">';
}
// insert buttons into myContainer
document.getElementById('myContainer').innerHTML = xBUTTONS;
</script>
first off, always attach events by using addEventListener. second, if you add an id to the button you dynamicly generate you can do something like this;
function click(){
alert(this.id+" clicked");
}
var but;
for (var i=0,e=100,i<e;++i){
but=document.createElement("input");
but.id=i;
...//make it into your button
but.addEventListener("click", click, false);
document.body.appendChild(but);
}

Categories