maxenglander
maxenglander

Reputation: 4041

iframe onload function undefined

I am developing a Rails application. One feature is providing customers the ability to preview HTML pages. I am loading these previews in an IFRAME, so that the CSS/styling of the preview container is separated from the CSS/styling of the preview itself. So far this works pretty well.

One problem I am having is auto-resizing the IFRAME once it has been loaded. I have this working great in Chrome just by attaching a function to the load event of the IFRAME via jQuery:

var show_preview = function() {
  $("#preview-loading").hide();
  $(this).show();
  this.style.height = this.contentWindow.document.body.scrollHeight + "px";
  return this.style.width = this.contentWindow.document.body.scrollWidth + "px";
}

$(function() {     
  return $("#preview_frame").load(function() {
    show_preview();
  });
});

This does not work very well in IE, however - the event appears not to be fired when the page first loads.

One work-around I am trying is to assign a function directly to the onload attribute of the IFRAME like so:

 <iframe onload="show_preview();" ...></iframe>

The problem I am having here is that the IFRAME cannot find the show_preview() function if it is defined in my JavaScript file. If I extract the function and put it in a SCRIPT tag above the IFRAME, everything works fine.

Appreciate any help - sure I am doing something bone-headed.

Max

Upvotes: 4

Views: 6017

Answers (1)

Alexander Danilenko
Alexander Danilenko

Reputation: 116

Attach your function to the window object, then it will be visible in your html code:

window.show_preview = function() { ... }

Upvotes: 3

Related Questions