Michael Sync

Michael Sync

Crisp, minimal personal blog

10 Oct 2006

JavaScript: Changing the image at runtime.


It’s the best way but if you are desperate, here is how you can do it. Note that the code doesn’t work on Web Server. In order to make this script to work, your have to add this page which is using this code as a trust site in Internet Explore 6 or 7. Of course, it won’t work in Mozilla-based browsers.. but the firefox extension called Noscript might help the script to work in Mozilla Firefox. (But I have tested yet.)

I discussed this code on the forum. You can read about it here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
   <head>
      <meta http-equiv="Content-Language" content="en-us">
      <meta name="GENERATOR" content="Microsoft FrontPage 6.0">
      <meta name="ProgId" content="FrontPage.Editor.Document">
      <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
      <title>New Page 1</title>
      <script language=javascript>
         /*
         Changing the image at runtime by using JavaScript.
         @imgId   : ID of Image HTML Control
         @strPath : The path of the image that you just browse.
         */
         function changePic(imgId,strPath){
         var o = document.getElementById(imgId);
         var s = new String(strPath);
         s = s.replace("\\","/");
         alert("file:///" + s);
         o.src="file:///" + s;
         }
      </script>
   </head>
   <body>
      <p>
         <img id=“img1″ border=”0″ src=”../sm_sunita.jpg” width=”300″ height=”225″>
      </p>
      <p>
         <input type=”file” name=”F1″ size=”20″ onchange=”changePic(‘img1′,this.value)”>
      </p>
      </form>
   </body>
</html>