Srujan Barai Srujan Barai - 5 months ago 7
CSS Question

make HTML page's element accessible in another HTML page

I have an HTML page say

main.html
which has an
iframe
(say
id="myFrame"
)showing
child.html
page. Both of these pages have a button called "Hide frame". The onclick of these buttons calls
hideFrame()
JS function which is declared in
main.js
file. The
hideFrame()
function just change the display of
myFrame
to "none".

function hideFrame(){
document.getElementById("myFrame").style.display = "none";
}


The
myFrame
is in
main.html
file so the button in
main.html
when calls the
hideFrame()
function, it works. The frame gets hidden. But the same is not working if I call the function from
child.html
page.

How can I access this element (
myFrame
) form
child.html
page?

Answer

you should use the main.html's window object to assign the function to. So instead of

function hideFrame(){
    document.getElementById("myFrame").style.display = "none";
}

you would do something like

window.hideFrame = function(){
    document.getElementById("myFrame").style.display = "none";
}

Now the function is globally scoped on main.html's window.

The child frame has it's own window object. You need access to the parent window object to call the function from child.html.

From main.html, you can call hideFrame normally on click onclick = hideFrame(), but in child.html, you should put onclick = window.parent.hideFrame()

Comments