Jump to content

getting elements out of an iframe


adam291086

Recommended Posts

I have a page that loads lots of images. These images are then used in another page within an iframe. I want to be able  to add an onclick function to each picture within the iframe. The onclick function will load the clicked image in full size below the iframe. 

 

Any ideas?

Link to comment
Share on other sites

I haven't done a whole lot with iframes, but I know the following:

 

-There is a DOM attribute on the iframe element called contentDocument, which you can use to access the stuff inside the iframe.

-The iframe has to be from the same domain as the parent page to access the information

 

More on the iframe dom: http://www.w3schools.com/htmldom/dom_obj_iframe.asp

 

Hope that helps get you going...

Link to comment
Share on other sites

Given both pages are in the same domain, you can add a function in the parent window to replace the source of the viewing image and call it from the iframe using "parent.FUNCTIONNAME()"

 

e.g.

Main page
<script type="text/javascript">
function replace_img(src){
   document.getElementById('display').src = src;
}
</script>
<iframe ....></iframe>
<img src="images/spacer.gif" id="display" border="0" alt="" />


Iframe page:
<img src="images/some_image.jpg" onclick="parent.replace_img("images/some_image_large.jpg");" border="0" alt="" />

Not tested

Link to comment
Share on other sites

The JavaScript to access an image inside the iframe from the parent to add an onclick would be:

 

var img = document.getElementById('iframe_id').contentDocument.getElementById('image_id');
img.onclick = function(){alert('clicked');}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.