Jquery – change iframe source in ie using javascript

iframejquery

I have used an iframe which looks like this:

<iframe style='width: 330px; height: 278px' scrolling='no' name="iframeId" class="advPlayer" id="iframeId" frameborder="0" src='../../player/iabpreview.php?adid=<?php echo $selectedAdIdx ?>&amp;autoPlay=true'></iframe>

Whenever I click on a <div>, I have to change the source of the iframe. I am using the following code:

if ($j.browser.msie) {            
  frames['iframeId'].window.location="../player/iabpreview.php?adid="+adId+"&autoPlay=true";
}else {
  $j(".advPlayer").eq(0).attr("src", "../player/iabpreview.php?adid="+adId+"&autoPlay=true");    
}

This works with Firefox, but not with Internet Explorer.

What code would work for Internet Explorer too?

Best Answer

You should never user 'browser detection', but feature detection. The most safe way imho is this:

function SetIFrameSource(cid, url){
  var myframe = document.getElementById(cid);
  if(myframe !== null){
    if(myframe.src){
      myframe.src = url; }
    else if(myframe.contentWindow !== null && myframe.contentWindow.location !== null){
      myframe.contentWindow.location = url; }
    else{ 
      myframe.setAttribute('src', url); 
    }
  }
}

Just test if the src property is available. If not, test on content window, and the last try is setAttribute.