kaginsmom
kaginsmom

Reputation: 1

Uncaught TypeError: Cannot set property 'src' of undefined

I know this was asked before but none of the answers given fixed my problem. Obviously a lot of people are getting the same errors with Chrome and Safari so I think an answer with an explanation would be benafitial if at all possable. My JavaScript teacher never taught only led us down the wrong path and said to forget that so I don't understand the code I have but I have to get it working in all browsers.

Here is my code:

<div class="gallery" align="center">
<h3>Simple and Effective Photo Gallery with HTML and JavaScript</h3><br/>
<div class="thumbnails">
<img onmouseover="preview.src=img1.src" id="img1" src="img1.jpg" alt="Image Not Loaded"/>
<img onmouseover="preview.src=img2.src" id="img2" src="img2.jpg" alt="Image Not Loaded"/>
<img onmouseover="preview.src=img3.src" id="img3" src="img3.jpg" alt="Image Not Loaded"/>
<img onmouseover="preview.src=img4.src" id="img4" src="img4.jpg" alt="Image Not Loaded"/>
<img onmouseover="preview.src=img5.src" id="img5" src="img5.jpg" alt="Image Not Loaded"/>
<img onmouseover="preview.src=img6.src" id="img6" src="img6.jpg" alt="Image Not Loaded"/>
</div><br/>
<div class="preview" align="center">
<img id="preview" src="img1.jpg" alt="No Image Loaded"/>
</div>
</div>  

Please HELP!!

Upvotes: 0

Views: 8847

Answers (4)

zloydadka
zloydadka

Reputation: 160

<script>
var prev;
function setPrev(img) {
prev = prev || document.getElementById('preview');
prev.src = img.src;
return false;
}
</script>    
<div class="gallery" align="center">
<h3>Simple and Effective Photo Gallery with HTML and JavaScript</h3><br/>
    <div class="thumbnails">
      <img onmouseover="setPrev(this)" id="img1" src="img1.jpg" alt="Image Not Loaded"/>
      <img onmouseover="setPrev(this)" id="img2" src="img2.jpg" alt="Image Not Loaded"/>
      <img onmouseover="setPrev(this)" id="img3" src="img3.jpg" alt="Image Not Loaded"/>
      <img onmouseover="setPrev(this)" id="img4" src="img4.jpg" alt="Image Not Loaded"/>
      <img onmouseover="setPrev(this)" id="img5" src="img5.jpg" alt="Image Not Loaded"/>
      <img onmouseover="setPrev(this)" id="img6" src="img6.jpg" alt="Image Not Loaded"/>
    </div>
    <br/>
    <div class="preview" align="center">
    <img id="preview" src="img1.jpg" alt="No Image Loaded"/>
    </div>
   </div> 

Upvotes: 0

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

document.getElementById("preview").src = "img1.jpg";

Upvotes: 3

Andrew
Andrew

Reputation: 6394

You can't change the src like that. Instead use:

document.getElementById('preview').src=.... 

Here is the simplest form of it :)

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23132

You can't just use an element's name in Javascript. You must get the DOM object corresponding to that element:

onmouseover="document.getElementById('preview').src=this.src"

Upvotes: 2

Related Questions