Script not working in either FF or IE

I am now up to “IF” and working on the assignment here;

JavaScript Primers #23

but the script below in their answer is not working on my end, help?

<body bgcolor="white" >
<center>
<h1>My Home Page</h1>
<SCRIPT type="text/javascript">
   var1="pic1.gif"
   var2="pic2.gif";
   var3="pic3.gif"
   now=new Date()
   num=(now.getSeconds() )%3
   num=num+1
   quot="'"   //this is double quote, single quote, 
   double quote which produces '
   document.write("Random Number: " + num + "<br>")
   if (num == 1)
       {cliche=var1} 
   if (num == 2)
       {cliche=var2}
   if (num == 3)
       {cliche=var3}
  document.write
  ("<img src=" + quot + cliche + quot +">")
</script>
<p>....describes my mood today.
</center>
</body>

</html>

Have you tried checking the error console?

I don’t know what to look for in there, I am seeing “All, Errors, Messages and Warning”?

Presumably we’re discussing FireFox. Click on Clear then reload your document then click on Errors.

This line is wrapped, and should be with the comment line above it.

double quote which produces '

You can put your code through jslint. JSLint,The JavaScript Code Quality Tool

Just copy and paste into the text box and hit the JSLint button

On the first go it comes up with this

Error:

Problem at line 1 character 19: Expected ';' and instead saw 'var2'.

var1="pic1.gif"

Problem at line 3 character 19: Expected ';' and instead saw 'now'.

var3="pic3.gif"

Problem at line 4 character 18: Expected ';' and instead saw 'num'.

now=new Date()

Problem at line 5 character 29: Expected ';' and instead saw 'num'.

num=(now.getSeconds() )%3

Problem at line 6 character 13: Expected ';' and instead saw 'quot'.

num=num+1

Problem at line 7 character 12: Expected ';' and instead saw 'double'.

quot="'" //this is double quote, single quote,

Problem at line 8 character 4: Expected an assignment or function call and instead saw an expression.

double quote which produces '

Problem at line 8 character 10: Expected ';' and instead saw 'quote'.

double quote which produces '

Problem at line 8 character 11: Expected an assignment or function call and instead saw an expression.

double quote which produces '

Problem at line 8 character 16: Expected ';' and instead saw 'which'.

double quote which produces '

Problem at line 8 character 17: Expected an assignment or function call and instead saw an expression.

double quote which produces '

Problem at line 8 character 22: Expected ';' and instead saw 'produces'.

double quote which produces '

Problem at line 8 character 32: Unclosed string.

double quote which produces '

Problem at line 8 character 32: Stopping. (47% scanned).

Implied global: var1 1, var2 2, var3 3, now 4,5, num 5,6, quot 7, double 8, quote 8, which 8

You could certainly do with adding in semicolons at the end of lines. It also chokes on your comment, as Paul pointed out.

RLM

Yay, JSLint! But be warned, it makes grown men cry.

For those who are not yet ready for the real thing ™, there is an alternative called JavaScript Lint that is much kinder on your feelings

For example:

[color="grey"] 1     var1="pic1.gif"
 2     var2="pic2.gif";
    [/color][color="black"]===^
    [/color][color="red"][b]lint warning: missing semicolon[/b][/color][color="grey"]
 3     var3="pic3.gif"
 4     now=new Date()
 5     num=(now.getSeconds() )%3
 6     num=num+1
 7     quot="'"   //this is double quote, single quote, 
 8     double quote which produces '
    [/color][color="black"]===^
    [/color][color="red"][b]SyntaxError: double is a reserved identifier[/b]
 [/color][color="grey"]9     document.write("Random Number: " + num + "<br>")
10     if (num == 1)
11         {cliche=var1} 
12     if (num == 2)
13         {cliche=var2}
14     if (num == 3)
15         {cliche=var3}
16    document.write
17    ("<img src=" + quot + cliche + quot +">")
[/color]

Even though, the code really should be tidied up further, in line with the advice from JSLint, with “The Good Parts” turned on.

Sorry, not understanding. In the Error console, I am seeing one error:

line 28; missing before statement
double quote which produces '

I don’t understand what is needed here, should the text “double quote which produces '” be removed from the script??

and in JS Lint I am seeing:

Error:

Problem at line 20 character 2: Unrecognized tag '<SCRIPT>'.

<SCRIPT type="text/javascript">

Problem at line 20 character 2: Stopping. (30% scanned).

I think the problem here is the word “script” has to be lowercase?

JSLint is for JavaScript. Not for HTML or CSS

GOT IT, works now, thanks! I am seeing <br> frequently in scripts now, is the same purpose as a break in HTML?

I am having trouble with the “num” in scripts, can anyone clarify please?

<SCRIPT type=“text/javascript”>
num=4
img1 = new Image ()
img1.src = “pic1.gif”
img2 = new Image ()
img2.src = “pic2.gif”
img3 = new Image ()
img3.src = “pic3.gif”
function slideshow()
{
num=num-1
if (num==0)
{num=3}

document.mypic.src=eval(“img”+num+“.src”)
}

Sorry, guess I did not include all info, in this primer:

JavaScript Primers #27

The assignment is asking to modify this script:

var num=1
  img1 = new Image ()
  img1.src = "pic1.gif"
  img2 = new Image ()
  img2.src = "pic2.gif"
  img3 = new Image ()
  img3.src = "pic3.gif"  
 function slideshow()
  {
   num=num+1
   if (num==4)
    {num=1}
 document.mypic.src=eval("img"+num+".src")
   }
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<IMG SRC="pic1.gif" NAME="mypic" BORDER=0 alt="">
<p>

<A HREF="JavaScript:slideshow()">
   Click for next picture</A>

so that the slideshow shows the pics in reverse order. This is their answer:


No need to rearrange the images, although you could. Just set it so that num loses one each time and when you get to zero, start again at three.

Here's the code:

<html>
<head>
<SCRIPT type="text/javascript">
    num=4
    img1 = new Image ()
    img1.src = "pic1.gif"
    img2 = new Image ()
    img2.src = "pic2.gif"
    img3 = new Image ()
    img3.src = "pic3.gif"  
    function slideshow()
    {
       num=num-1
       if (num==0)
          {num=3}
      document.mypic.src=eval("img"+num+".src")
    }
</script>
</head>
<body>
<center>
<img src="pic1.gif" name="mypic" border=0>
<p>
<a href=
 "JavaScript:slideshow()">Click for next picture</a>

I am not understand all of the “num” functions in this, especially why not simply change the order of the pics so how are the num’s actually reversing the order of the pics?

Any idea why this script taken from this tutorial:

JavaScript Primers #28

is not working please?

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
 var num=1
 img1 = new Image (150,150)
 img1.src = "pic1.gif"
 img2 = new Image (150,150)
 img2.src = "pic2.gif"
 img3 = new Image (150,150)
 img3.src = "pic3.gif"  
  function startshow()
  {
   for (i=1; i<20; i=i+1)
{document.mypic.src=eval("img"+num+".src")
    for(x=1; x<800; x=x+1)
  {}
    num=num+1
    if(num==4)
    {num=1}
   }
   document.mypic.src=img1.src
   }
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<IMG SRC="pic1.gif" NAME="mypic" BORDER=0 alt="">
<p>

<A HREF="JavaScript:startshow()">
   Display animation</a> 

</CENTER>
</BODY>
</HTML>

That’s is some mighty old code there that could do with a serious update, but I would put my finger on {} being the cause of the problem.
It seems that the code is trying to use that as a delay loop, but computers are so fast now that it doesn’t do the job.

A reworking of the code using setTimeout might be viable, but it’s also a good opportunity to improve on the rest of it as well.

Here’s a minimal update after the images are set up, so that the slideshow calls a function that uses setTimeout to loop itself.


function startshow()
{
  i=1;
  showNextImage();
}
function showNextImage()
{
  document.mypic.src=eval("img"+num+".src")
  i=i+1
  num=num+1
  if(num==4)
  {num=1}
  if (i<20)
    setTimeout(showNextImage,100)
  else
    document.mypic.src=img1.src
}

However, the code monkey in me screams “Horrible!” to the overall techniques that are being used.

Here’s an extensive update of the whole example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Animation</title>
    <style type="text/css">
    body {
        text-align: center;
    }
    #mypic {
        border: 0;
    }
    </style>
</head>
<body>
<p><img id="mypic" src="pic1.gif" alt=""></p>
<p><a id="displayanimation" href="#mypic">Display animation</a></p>
<script type="text/javascript">
(function () {
    function preload(images) {
        var image = new Image(),
            i;
        for (i = 0; i < images.length; i += 1) {
            image.src = images[i];
        }
    }
    function showNextImage(mypic) {
        var num = mypic.counter % mypic.images.length;

        mypic.src = mypic.images[num];

        if (mypic.counter < 20) {
            mypic.counter += 1;
            window.setTimeout(function () {
                showNextImage(mypic);
            }, 100);
        } else {
            mypic.src = mypic.images[0];
        }
    }
    function startshow(images) {
        var id = this.href.split('#')[1],
            mypic = document.getElementById(id);
        
        mypic.images = images;
        mypic.counter = 0;
        showNextImage(mypic);
    }

    var images = ['pic1.gif', 'pic2.gif', 'pic3.gif'],
        link = document.getElementById('displayanimation');
        
    preload(images);

    link.onclick = function () {
        startshow.call(this, images);
        return false;
    };
}());
</script>
</body>
</html>

Sorry to hijack this. Interested in your script Paul. Would love to know the thinking behind the design. Something that has me scratching my head.

Are there advantages to adding the properties to the element? Is it a scoping consideration?

I’ve had a play with the script and removed the startShow function. There’s a word going through my head more and more of late though and that’s ‘abstraction’. Essentially is that what I’m wrongly doing? Removing a layer of abstraction? Still sketchy about this stuff.

Just for mikehende’s info % is a modulus. some info here javascript string and arithmetic operators - javascript variables and expressions

(function (global, doc) {

    var images = ['pic1.gif', 'pic2.gif', 'pic3.gif'],
        link = doc.getElementById('displayanimation'),
        mypic = doc.getElementById(link.href.split('#')[1]),
        imglen = images.length,
        counter = 0;
        
    (function preload(images, len) {
        var image = new Image(),
            i;
        for (i = 0; i < len; i += 1) {
            image.src = images[i];
        }
    }(images, imglen));
    
    function showNextImage(mypic) {
        var num = counter % imglen;
 
        mypic.src = images[num];
 
        if (counter < 20) {
            counter += 1;
            global.setTimeout(function () {
                showNextImage(mypic);
            }, 100);
        } else {
            mypic.src = images[0];
        }
    }
 
    link.onclick = function () {
        counter = 0;
        showNextImage(mypic);
        return false;
    };
}(window, window.document));

Cheers RLM

For the most part. My aim there was to completely remove the global variables, which allows it to be used multiple times on the page if need be.
There isn’t much that needs to know about the counter and the images, so storing them as properties on the the image section itself seems to be a useful solution there.

It wouldn’t take much more effort to make it more widely accessible, by passing the link and the images to an init section.

Thanks Paul. Much appreciated.

This is way too much for me guys :), I tried this one here instead:

Creating an image slide show (Two parts)

From the script :

//variable that will increment through the images
var step=1
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step<3)
[B]step++[/B]
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()

Can you guys explain the step++ please?

Re-written twice. Once with comments and once without.

You need to pick up on the use of brackets{} and semi-colons; especially when starting out.

I know these older tutorials seem to have omitted this syntax.

I’ve made a few simple changes, but tried to keep close to the original.

I would say eval should only be used when you really know what you’re doing and in special circumstances. Genarally there’s an alternative.

step++ just means add 1. could be written step += 1 or step = step + 1.

the setTimeout doesn need to have slideit() in quotes. As you are not passing parameters to the function just the name will suffice.

if you do need to pass parameters/arguments you can do it like this and use an anonymous function.

setTimeout( function(){ slideit(‘a’, ‘b’, 3 ); }, 2500 );

It takes a bit of time to grasp this stuff. I know.

Really you need to try and find some more up to date tutorials. There is a course that is part of this site ‘JavaScript Programming for the Web’, which is possibly worth looking into. https://learnable.com/sitepoint?utm_source=sitepoint&utm_medium=channel&utm_campaign=sitepoint

//variable that will increment through the images
var step=1,
    // Alternative shortand. images = [ firstcar, secondcar, thirdcar ]
	images = new Array( firstcar, secondcar, thirdcar ),
	numOfImages = images.length; // 3
	  
function slideit(){
  //if browser does not support the image object, exit.
  if (!document.images) { return }

  document.images.slide.src = images[step] + '.gif';

  if (step < numOfImages) { // is step smaller than the number of images?
    step++; // yes, then step = step + 1. can be shortened to step += 1.
  } else {
    step = 1; // if not i.e. in this case 4. reset step.
  }
  //No need for 'slideit()'. slideit will do here.
  setTimeout(slideit, 2500);
}

slideit();
// Less comments so it's clearer where to use brackets { statement block } and semi-colons;
// variable definitions are split by commas and end in a semi-colon;
// e.g. var a = 1, b = 2, c = 3;
var step=1,
	images = new Array( firstcar, secondcar, thirdcar ),
	numOfImages = images.length;
	  
function slideit(){
  if (!document.images) { return; }

  document.images.slide.src = images[step] + '.gif';

  if (step < numOfImages) {
    step++;
  } else {
    step = 1;
  }
  setTimeout(slideit, 2500);
}

slideit();

RLM