28 April 2010

Javascript: Set or get URL/URI/src/href of an iframe or frame/frameset function

This function simply targets an iframe or frameset and retrieves or changes it's src or href attribute.

Tested in FF 3.6 and Chrome (might need some tweaking for IE)

The Function: (Please see right hand pane before copying my code - thank you! >>>)

/*loads a url in the specified frame/iframe or returns the loaded url if url arg is blank
frame  //DOM reference to a frame/iframe or string ID of an iframe in this document
url  //url to href to. ignore or set=0 to return current url of page
function framehref(frame,url){
 if(typeof(frame)=='string'){//find iframe (will not find a frame):
  if(url==undefined){ return( frame.contentWindow.document.location );}
  if(url==undefined){ return( frame.document.location );}

//sample usage:
alert(framehref('myIframe')); //alerts the current location of the iframe 
framehref('myIframe',"http://www.google.com/"); //sends the iframe to google homepage
framehref(top.right,"http://www.google.com/"); //sends the right hand frame (in a frameset) to google homepage


Post a Comment

Cron Design Studio: Dublin based web design & software development