Click to See Complete Forum and Search --> : setting src using javascript


Sul
10-19-2003, 05:00 PM
Hi

I have an iframe in which a picture loads. I'm trying to load a picture in there using javascript - e.g. document.iframename.src = picture.jpg.

For some reason this isn't working...

Also, how do you call functions in the html - e.g. on an onclick event?

fredmv
10-19-2003, 05:50 PM
I have an iframe in which a picture loads. I'm trying to load a picture in there using javascript - e.g. document.iframename.src = picture.jpg.
Your syntax appears to be incorrect. I'll explain what's basically wrong. Well, in this case, the src attribute of an iframe should be a string. This means that it needs to be quoted. You should also be assigning your iframe an id attribute, then using JavaScript's getElementById method to access it, along with the iframe's contentDocument property. So, here's what your code should basically look like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>untitled</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1" />
</head>
<body>
<div>
<iframe src="about:blank" id="test" style="height: 200px; width: 350px;"></iframe>
<hr />
<a href="#" onclick="document.getElementById('test').contentDocument.location='http://www.usor.state.ut.us/ucat/fundpres/texture.jpg';">texture.jpg</a>
</div>
</body>
</html>
Also, how do you call functions in the html - e.g. on an onclick event? Check above, that link executes JavaScript code inside it's onclick event handler. ;)

I hope that helps you out.

Sul
10-20-2003, 02:51 AM
Thanks. That makes a lot of sense :) I'm not at my computer right now, so I can't test it. However, I also need to call a function such as getpicture() on an onclick event, is this syntax correct:

<a href="#" OnClick=getpicture()>

?

Thank you.

fredmv
10-20-2003, 09:29 AM
You're welcome. ;)

Yes, that will work properly. However, I would recommend quoting all attribute values since in the future, it will most likely be required:<a href="#" onclick="getpicture();">Link text here.</a>I hope that helps you out.

Sul
10-20-2003, 02:06 PM
Thanks, it's all working now. Except, I modified your suggestion to getElimentById('id').src.

fredmv
10-20-2003, 02:46 PM
No problem! Yes, either way is completely valid. You could also use the setAttribute method as well. For example:document.getElementById("foo").setAttribute("src", "location.html");