Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Newbie problem with simple image swap

    Lets say I have two images in a box

    Code:
    <body>
    
    <div id="box">
    
    <img src="image1.jpg" id="image1" width="100" height="100" />
    <img src="image2.jpg"  id="image2" width="100" height="100" />
    
    </div>
    
    </body>
    When I click on Image1 I want Image2 to get replaced with a new image, called Image3.

    So I tried this code:

    Code:
    var image1 = document.getElementById("image1");
    image1.onclick = image1_click ();
    
    function image1_click () {
    	new_image= new Image
    	new_image = document.getElementById("image2");
    	new_image.src="image3.jpg"
    }
    But instead of replacing the image on click, from some reason it replaces image2 with image3 from start/load.

    What should I do to make this work?
    Thank you.

  • #2
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Try this

    Code:
    function imageClick(ID,Image) {
      new_image = document.getElementById(ID);
      if(new_image) {
        new_image.src = Image;
      }
    }
    
    window.onload = (function(){
      document.getElementById("image1").onclick = (function(){
         imageClick('image2','image3.jpg');
      });
    });
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • Users who have thanked DJCMBear for this post:

    EnfantSauvage (12-14-2010)

  • #3
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thank you, that works perfectly


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •