Loading an Image Using JavaScript

June 25, 2007

JavaScript is a two-step process:

1. Create an Image object and assign it to a variable:

var myImage = new Image;

2. Assign a source image URL to the src attribute of the object:

myImage.src = “image URL goes here”;

The following task illustrates the programmatic loading of an image by loading

an image in this way and then providing links to display the height and width of

1. Create a script block with opening and closing script tags.

2. In the script, create a new Image object named myImage:

myImage = new Image;

3. Load the image by assigning its URL to the src attribute of

myImage:

myImage.src = image1.jpg;

4. In the body of the page’s HTML, include a link for displaying the

width and add an onClick event handler to the a tag; this eventhandler will use the

window.alert method to display the image’s

width in a dialog box. The image’s width is obtained by referring to

document.myImage.width:

<a href=#” onClick=window.alert(document.myImage.width)Æ

”>Width</a><br>

5. Include a link for displaying the height, and add an onClick event

handler to the a tag; this event handler will use the window.alert

method to display the image’s height in a dialog box. The image’s

width is obtained by referring to document.myImage.height. The

final page should look like the following:

<script language=JavaScript”>

myImage = new Image;

myImage.src = Tellers1.jpg;

</script>

<body>

<a href=#” onClick=window.alert(myImage.width)

”>Width</a><br>

<a href=#” onClick=window.alert(myImage.height)

”>Height</a>

</body>

Entry Filed under: Javascript. .

4 Comments Add your own

  • 1. ewrewre  |  June 7, 2008 at 11:08 am

    ewrewr

    Reply
  • 2. Remy  |  September 2, 2009 at 11:52 am

    Thnx loads, verry usefull

    Reply
  • 3. Devilslab-Your guide to stay updated  |  September 12, 2009 at 7:59 am

    great post.. like the way you use js

    Reply
  • 4. SangraM  |  October 22, 2009 at 7:08 am

    very good………………… i like it it is very useful

    Reply

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Spam Blocked

Flickr Photos

eight.

The edge of a Dutch kingdom

I'm still standing................. yeah yeah yeah

More Photos

Blogroll

Recent Posts

Recent Comments

izdelava spletnih st… on min-height hack/workaround in …
kathmandu flights on iframe change src | javas…
Ali A. Akbar on min-height hack/workaround in …
izdelava spletnih st… on WordPress Themes
izdelava spletnih st… on Top 25 medical colleges

Pages

Top Clicks

Top Posts

Blog Stats