Search code examples
javascripthtmlcssiframeparent

Apply scripts and styles to iFrame?


I'm trying to create a small editor for a website. One of the features is a drag and drop interface. I'd like for the user to be able to drag elements to another position in the page. I was thinking of having an iFrame of the site, and applying JS and CSS to enable drag and drop ability.

Here's a screenshot of a CMS that does that:

CMS

The site is an iFrame. When I open the iFrame, you can't drag and drop elements. So, I'm assuming that they somehow apply changes in the parent page. Is there any way that I can basically add Javascript into the iFrame?

Thanks!


Solution

  • As long as the page that the iframe references is on the same domain, yes, you can. You can apply scripting and styling on elements within your iframe just like you'd do to any element in your main parent page. The main syntax is this:

    var ifrm = document.getElementById("your_iframe_id");
    /*ifrm.contentWindow.document is the document within the iframe
    so let's try styling a div with an id 'mydiv' inside the iframe:*/
    ifrm.contentWindow.document.getElementById("mydiv").style.color = "red";
    

    Of course this is just a sample, you can use the same mechanism to do more complex stuff with elements within the iframe (including drag and drop!)

    You could, as well, execute functions that are defined within the iframe from the parent page. The syntax is similar and intuitive:

    ifrm.contentWindow.yourFunction();
    

    I hope that helped you in any manner!