JavaScript and Ajax for the Web, Sixth Edition

A useful tool for designers is the ability to view all the images on a page, apart from the layout of the page. Script 17.8 allows you to peek behind the scenes of someone else's page and see a list of the page's individual images, the height and width of the images (in modern browsers), and their URLs.

Script 17.8. You can view a table of page images with this script.

[View full width]

javascript:var imgWin,i,outText='',di=document. images;for (i=0;i<di.length;i++){if( outText. indexOf(di[i].src)<0){outText+='<tr><td> <img src='+di[i].src+'/></td><td>'+di[i]. height+'</td><td>'+di[i].width+'</td> <td>'+di[i].src+'</td></tr>'}};if(outText ==''){alert('No images!');}else{imgWin= window.open('','IW','width=800,height=600, scrollbars=yes');void(imgWin.document.body. innerHTML='<table border=1 cellpadding=10> <tr><th>Image</th><th>Height</th><th>Width </th><th>URL</th></tr>'+outText+'</table>');}

To view images:

1.

javascript:var imgWin,i,outText= '',di=document.images;

The bookmarklet starts and initializes four variables : imgWin ; i ; outText , which will later contain all the output; and di , which contains the document.images object.

2.

for (i=0;i<di.length;i++){

We now loop through each image in the document.

3.

if(outText.indexOf(di[i].src)<0){

In this step, we check to see if we've already put the image on the page. This line of code keeps that from happening more than once.

4.

[View full width]

[View full width]

outText+='<tr><td><img src='+di[i]. src+'/></td><td>'+di[i].height+ '</td><td>'+di[i]. width+'</td><td>' +di[i].src+'</td></tr>'}};

All the information we want is written out here, in a nice table format. The first cell contains the image; the second contains the height; the third, the width; and the last contains the URL of the image.

5.

if(outText==''){

When the loop completes, check to see if we've found any images.

6.

alert('No images!');

If there weren't any images found in step 5, an alert window that says "No images!" is displayed.

7.

else{imgWin=window.open('','IW', 'width=800,height=600,scrollbars= yes');

If we found images, open up a new window for the image information.

8.

[View full width]

[View full width]

void(imgWin.document.body. innerHTML='<table border=1 cellpadding=10><tr><th>Image </ th><th>Height</th><th>Width </th><th>URL</th></tr>'+outText+ '</table>');}

Here is where the new window is created and displayed. The image information, with heading information for each column, is written out, as shown in Figure 17.16 .

Figure 17.16. This script formats the images and information into an attractive table.

Категории