Introduction
Nowadays, iframe
element is not very popular but I think many web developers still use it for their web layout. As we know, iframe
is very useful for web developers to implement their website especially in business web application. In previous projects, I often used iframe
as well. So today, I wrote a sample to demonstrate how to use jquery in iframe
element.
My sample includes two pages, which are parent and child page. The parent page contain an iframe
element and several buttons to trigger my defined function to interact with the child page.
The functions are as follows:
Parent.html
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<iframe id="childframe" height="300"
width="300" src="child.htm" frameborder="1"></iframe>
<script type="text/javascript">
$(document).ready(function() {
setText =function(){
$('#childframe').contents().find('#child_text_input').val('called by parent frame!');
}
getText =function(){
alert($('#childframe').contents().find('#child_text_input').val());
}
redirectURL = function(){
$('#childframe').attr('src','http://jquery.com/');
}
callChild = function(){
$('#childframe')[0].contentWindow.showmsg();
}
replymsg = function(){
alert('This function called by child page.');
}
});
</script>
<br />
<input type="button" onclick="setText()"
value="Set Text into child textfield" />
<input type="button" onclick="getText()"
value="Get Text into child textfield" />
<input type="button" onclick="callChild()"
value="Call child page function" />
<input type="button" onclick="redirectURL()"
id='urlButton' value="Set child url" />
</body>
</html>
The following demo code is child.html. It includes two buttons which will use onclick
event to call my defined functions to interact with parent page.
The function 'callParent
' is used to call the function 'replymsg
' in parent page in order to display a popup
message.
Another function 'setButtonText
' is used to find out a button, whose id is 'urlButton
' in parent page. And then update the button value. (* The function in my code also has other two methods for reference. you can uncomment them to use as well.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<input type="text" name="child_text_input"
id="child_text_input" >
<input type="button" onclick="setButtonText()"
value="Set Text into parent button text" />
<input type="button" onclick="callParent()"
value="Call parent page function" />
<script type="text/javascript">
$(document).ready(function() {
showmsg = function(){
alert('This function called by parent page.');
}
callParent = function(){
parent.replymsg();
}
setButtonText = function(){
$(parent.document).find('#urlButton').val('value changed by child page');
}
});
</script>
</body>
</html>
I tested the above code in Internet Explorer 11.