Reputation: 306
Can anyone advise why this code isn't working when I click the link?
The link is in an iframe and I want the link to toggle a menu in the Main page.
<script>
$(document).ready(function() {
quickout = 0;
$("#scrollsetting").click(function(){
if (quickout==0){
window.parent.document.getElementById('quickmenu').show(300);
quickout = 1;
} else {
window.parent.document.getElementById('quickmenu').hide(300);
menuout=0;
}
})
});
</script>
Upvotes: 2
Views: 5548
Reputation: 70169
The jQuery selectors do not select elements in other windows naturally, you have to either access the jQuery in the other window to query its DOM or pass a reference to the other window's document so jQuery can find what you're looking for.
First approach, querying the element inside the iframe
's window with the jQuery inside the iframe
, and the one in parent window with the parent window's jQuery:
$(document).ready(function () {
$("#scrollsetting").click(function () {
window.parent.$('#quickmenu').toggle(300);
});
});
Though, it is not always necessary to load jQuery twice, so let's say you just loaded it in the parent window, you can then use the parent's jQuery with a context selector setting it to the current document
, while it still defaults to the parent window's document when omitted:
var $ = window.parent.$;
$(document).ready(function () {
$("#scrollsetting", document).click(function () {
$('#quickmenu').toggle(300);
});
});
Likewise, if for some reason you'd have jQuery solely in the children window, use a context selector when referencing the parent window's document:
$("#scrollsetting").click(function () {
$('#quickmenu', window.parent.document).toggle(300);
});
ps. Don't mind my inject
wrapper. It is just a way to write code in a readable manner before injecting its text into the iframe
in the form of an IIFE - my string concatenation implicitly calls Function.toString()
.
Of course, if you have other dependencies/plugin that absolutely require jQuery included in the framed page, you can go with the first solution which is the simplest, or whichever you find more suitable.
ps2. If any reader has a problem trying this code in your pages, remember that iframe
s are subject to the same origin police. That is, you can't access an iframe
when its src
's domain, protocol or port doesn't match the parent document's, and the same for the other way around.
Upvotes: 6