I have a main (parent) page that hosts 3 iframes that are under the same domain. The iframe's src attribute is added on a click event, so the iframe's aren't loaded until needed.
What I want is when I click a certain div on my main page, it will trigger a click on a specific div that's located inside all 3 iframes at the same time.
I have tried the following code in my parent page:
function myFunction() {
var iframe = document.getElementById("iframe1");
var elmnt = iframe.contentWindow.document.getElementById("btn").click()
}
and repeated it twice more for iframe's #iframe2 and #iframe3. However, it didn't work unless I loaded the iframes in order that they're written on my page. (i.e the click event on #iframe2 didn't execute until after #iframe1's event). This is a problem as I'm unable to control what iframe visitors will load first. I tried giving them separate function() names, but the same thing occurred - only one iframe was effected at a time. Note, this worked fine when I tested it out with the iframe's already having their src's like normal, just not when they're added manually.
I also tried adding this in the iframe pages:
parent.document.getElementById('btn').onclick = function(){
document.getElementById('btn').click();
}
However, this only works on the first iframe that is loaded (i.e if #iframe2 is loaded first, then the iframe1's and iframe3's event wont execute)
Is there any other solutions I could try? My purpose is creating a day and night toggle with classList.toggle, and I want all the iframes css to be toggled at the same time, with the toggle button
being on the main page.
(I prefer vanilla javascript for my main page, but am fine with jQuery on the iframe pages)
You are dynamically loading iframe's src suppose user loads <iframe3> but your code is written such a way that it tries to do something with <div> inside <iframe1> (which isn't loaded yet) what will happen? It will throw error and break the execution that's why it's not working for you what you need is to first look whether they are currently there
Also you are using var iframe = document.getElementById("iframe1"); but I don't see any id on the fiddle you posted
Try this
<body>
<style>
body {
background:#fff;
color:#000
}
body.toggled
{
background:#000;
color:#fff
}
</style>
<div id="btn">click here to toggle css</div>
<p>page content</p>
add src to iframe one<br>
add src to iframe two<br>
add src to iframe three
<p>iframe 1:</p>
<iframe src="about:blank" id="iframe1" name="iframe1"></iframe>
<p>iframe 2:</p>
<iframe src="about:blank" id="iframe2" name="iframe2"></iframe>
<p>iframe 3:</p>
<iframe src="about:blank" id="iframe3" name="iframe3"></iframe>
</body>
<script>
document.querySelector('#btn').addEventListener('click', function(e) {
[].map.call(document.querySelectorAll('body,a'), function(el) {
el.classList.toggle('toggled');
});
var iframe1 = document.getElementById("iframe1");
var iframe1btn = iframe1.contentWindow.document.getElementById("btn");
if(iframe1btn) //<-- check if that element really exists within <iframe>
iframe1.contentWindow.document.getElementById("btn").click()
// you could've also used <iframe>'s loaded event but this is better way
var iframe2 = document.getElementById("iframe2");
var iframe2btn = iframe2.contentWindow.document.getElementById("btn");
if(iframe2btn)
iframe2.contentWindow.document.getElementById("btn").click()
var iframe3 = document.getElementById("iframe3");
var iframe3btn = iframe3.contentWindow.document.getElementById("btn");
if(iframe3btn)
iframe3.contentWindow.document.getElementById("btn").click()
});
</script>
I am not particularly sure what you got wrong on, but I think I understand what you want to do. To reproduce this example, please create a HTML file (with name index.html) in your local PC and run this file on your browser:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #fff;
color: #000;
}
body.toggled {
background: #000;
color: #fff;
}
</style>
</head>
<body>
<div id="btn">click here to toggle css</div>
<p>page content</p>
add src to iframe one<br>
add src to iframe two<br>
add src to iframe three
<p>iframe 1:</p>
<iframe src="about:blank" name="iframe1"></iframe>
<p>iframe 2:</p>
<iframe src="about:blank" name="iframe2"></iframe>
<p>iframe 3:</p>
<iframe src="about:blank" name="iframe3"></iframe>
<script>
let outerBody = document.querySelector('body')
let toggleButton = document.querySelector('#btn')
let iframes = document.querySelectorAll('iframe')
let anchors = document.querySelectorAll('a')
toggleButton.addEventListener('click', () => {
let body = document.querySelector('body')
body.classList.toggle('toggled')
Array.from(iframes).forEach(iframe => {
toggleIframe(iframe)
})
})
Array.from(iframes).forEach(iframe => {
iframe.addEventListener('load', e => {
toggleIframe(iframe)
})
})
Array.from(anchors).forEach(anchor => {
anchor.addEventListener('click', e => {
let targetedIframe = document.querySelector(`iframe[name=${anchor.target}]`)
targetedIframe.src = './index.html'
})
})
function toggleIframe(iframe) {
let iframeBody = iframe.contentWindow.document.querySelector('body')
let iframeToggleButton = iframe.contentWindow.document.querySelector('#btn')
let isOuterBodyToggled = outerBody.classList.contains('toggled')
let isIframeBodyToggled = iframeBody.classList.contains('toggled')
if (isOuterBodyToggled && iframeToggleButton && !isIframeBodyToggled)
iframeToggleButton.click()
else if (!isOuterBodyToggled && iframeToggleButton && isIframeBodyToggled)
iframeToggleButton.click()
}
</script>
</body>
</html>
I changed your a's href to empty (#). I also changed your JS file. Basically, I specified the as to change the source of its associated iframe when it's clicked with addEventListener('click'). Also, each time I click on the outerBody's (parent browsing context) button, I will also toggle its containing iframes' body by performing a click on the iframes' buttons. That already works. However, your problem was that you don't know when the iframes will be loaded. There's a function for that, addEventListener('load') on your iframes. When an iframe is loaded (an iframe will be loaded again when its source is changed), I will use that event listener to check if its parent browsing context's body is toggled. If it is, then simply toggle the iframe's body too by performing click.
Voila, it works. As mentioned, please try pasting the code above to your local file in your PC and run it in a browser.
How i can append attach on iframe with src adress?
How i can manipulate div attaching on it iframe object with content?!
(Included into Wordpress page) by using brackets for testing....
I want to make custom js included into wordpress page without use jquery
(if u have any ideas cause i read the wordpress does support jquery libraries) could be good. I accept and jquery too as idea. I choose to do not use jquery cause i think wordpress does not support it.
javascript
<script async="" type="text/javascript">
var Divfrm = document.getElementById('#frame');
var ifrm = document.createElement('iframe');
function evtTrigger(){
document.addEventListener('click',function(e){
e.preventDefault();
Divfrm = document.appendChild(ifrm);
ifrm.setAttribute('src','http://google.com');
});
function close(){
ifrm = document.Detach(Divfrm);
};
return DivFrm = document.InnerHTML = ('');
</script>
html
<!--I'din't know why worpress cover field "script" tag?!-->
<h1 style="color: aqua; text-align: left;">Magic fountain mod example script</h1>
<p style="color: aqua; text-align: left; margin-left: 20px;">Can you ever saw glow fountain?, that was is available now</p>
<div id="frame" style="outline-color: mediumturquoise; background: rgba(0,128,128,0.2); overflow-y: scroll; height: 400px; margin-top: 20px; margin-bottom: 30px; color: mediumaquamarine;">
<!--here div was as role dialog ^^^>
<p>Explanation about code here text</p>
</div>
<div>
<button onclick="evtTrigger()">Show video</button>
<button onclick="close()">Hide this</button>
</div>
When the user clicks Show Video, it will call evtTrigger() -- but all that function does is attach the click listener to the document, it doesn't run that handler function. In fact, after clicking Show Video, after that every click on the page will run your handler function.
You're also appending the iframe to the entire document, not just your div (hence you're using document.appendChild instead of Divfrm.appendChild) -- that's probably not what you want.
So remove your addEventListener code, put the iframe appending code directly in the evtTrigger function, and change Divfrm = document.appendChild(ifrm) to just Divfrm.appendChild(ifrm). Then it should work.
Question is really unclear. I assume you want to add the ifrm inside Divfrm on clicking somewhere which fires the evtTrigger function. And then remove the ifrm when calling close()
If this is your goal, try this
var Divfrm = document.getElementById('#frame');
var ifrm = document.createElement('iframe');
function evtTrigger(){
Divfrm.appendChild(ifrm);
ifrm.setAttribute('src', 'http://google.com');
};
function close(){
Divfrm.removeChild(ifrm);
};
By the way, you can't load google.com inside your iframe because browser won't allow it. If this is just as an example, then it's fine.
There is a frame were a website will open i want that all links in the website is disabled except the one link suppose it to be a login link. Is it possible to disable all the links except one. So,this is what that is required.
<a href="" id="link_t" >link for exam</a>
<iframe id="frame" style=" width:100%; height: 700px; margin:30px 0 0 0px;
border-style: none; " src="" ></iframe>
on js file code is
var link_on_page=document.getElementById('link_t');
var divv=document.getElementById('frame');
link_on_page.addEventListener('click', function(e) {
e.preventDefault();
divv.src= "some_link";
requestFullscreen(document.documentElement);
});
I am calling third part website in a frame and do not want that links should open just the login link only just want to diable all links except the one on the third party website.
Disabling all links can except one can be accomplished like so:
function disableAllLinks(){
// x now contains a live collection of anchor elements
let x = document.getElementsbyTagName('a');
let j = 0;
while (x[j]){
x[j].setAttribute('href', '');
j++
}
Then enable the reference you want using the same idea but with
x = document.getElementbyId('someId');
x.setAttribute('href', 'linkgoeshere');
This is just a quick simple example that uses the DOM
You would then include a call to the function in the 'onclick' event function that loads the new page.
I am normally used to "window.open" to open a popup window into a new URL. How can open a window into a new URL, shadow out/grey out the current window, and on close remove the shadow background.
Is it best to use jQuery to do this? Could I use the default libraries without use jquery plugins?
I want to do something like this and then "disable" my shadow on unload. Hopefully that uses core jQuery libraries or standard javascript calls. I want to avoid using any plugins besides jQuery.
var popup = window.open('http://google.com', 'popup');
showShadow();
$(window).unload(function() {
if(!popup.closed) {
disableShadow();
}
});
Basically, you can open the popup and set that window the beforeunload. In short, something like this:
popup = window.open("", "name", "width=400, height=300")
popup.onbeforeunload = function() { $('#shadow').hide();}
I created a fiddle for you.
http://jsfiddle.net/DDksS/
So you want to build your own modal box using jQuery instead of using an existing plugin? ...OK, let's play (as it was already pointed out, using popups is not a user-friendly solution):
Your check list :
- the trigger
- the shadow layer
- the modal box size and position
- add content to modal and display it along the shadow
1) The trigger is a simple html link to open the content inside the modal
open url
... we will pass the size of the modal via data-width and data-height (HTML5) attributtes.
2) The shadow layer is the html structure that we will append to the body after the trigger. We can set the structure in a js variable
var shadow = "<div class='shadow'></div>";
3) As we mentioned, the size of the modal is set through some data-* attributes in the link. We would need to do some math
var modalWidth = $(this).data("width");
var modalHeight = $(this).data("height");
var modalX = (($(window).innerWidth()) - modalWidth) / 2; // left position
var modalY = (($(window).innerHeight()) - modalHeight) / 2; // top position
NOTE : $(this) is our trigger selector .myModal that we'll get inside an .on("click") method later on. BTW, the .on() method requires jQuery v1.7+
4) Now we need to create the modal's html structure and pass the content href. We'll create a function
function modal(url) {
return '<div id="modal"><a id="closeModal" title="close" href="javascript:;"><img src="http://findicons.com/files/icons/2212/carpelinx/64/fileclose.png" alt="close" /></a><iframe src="' + url + '"></iframe></div>';
}
... as you can see, our structure contains a close button to remove the modal and the shadow layer. The function also gets a parameter when is called (url) which allows to set the src attribute of the iframe tag.
NOTE : we have to use the iframe tag to open external urls, however we should always consider the same origin policy and other security restrictions when using iframes.
So now, we need to put together all the events after we click on our .myModal trigger, which are appending both the shadow and the modal box to the body and to remove them when we click on the close button so
$(".myModal").on("click", function(e) {
e.preventDefault();
// get size and position
modalWidth = $(this).data("width");
modalHeight = $(this).data("height");
modalX = (($(window).innerWidth()) - modalWidth) / 2;
modalY = (($(window).innerHeight()) - modalHeight) / 2;
// append shadow layer
$(shadow).prependTo("body").css({
"opacity": 0.7
});
// append modal (call modal() and pass url)
$(modal(this.href)).appendTo("body").css({
"top": modalY,
"left": modalX,
"width": modalWidth,
"height": modalHeight
});
// close and remove
$("#closeModal").on("click", function() {
$("#modal, .shadow").remove();
});
}); // on
STYLE : of course we will need some basic CSS style to make our modal elements work properly:
.shadow {width: 100%; height: 100%; position: fixed; background-color: #444; top: 0; left:0; z-index: 400}
#modal {z-index: 500; position: absolute; background: #fff; top: 50px;}
#modal iframe {width: 100%; height: 100%}
#closeModal {position: absolute; top: -15px; right: -15px; font-size: 0.8em; }
#closeModal img {width: 30px; height: 30px;}
* SEE DEMO *
BONUS : you could also bind a keyup event to close the modal using the escape key
$(document).keyup(function(event) {
if (event.keyCode === 27) {
$("#modal, .shadow").remove();
}
}); //keyup
LAST NOTE : the code is subject to many improvements and optimization but is a basic layout of what many lightboxes do. My last recommendation : use fancybox for more advanced functionality ... sometimes it doesn't worth the effort to re-invent the wheel ;)
Using Javascript to create new popup windows is so 1990's, not to mention not very user-friendly. What you're looking for, both UI-wise and looks-wise is a modal dialog; there's billions of examples and pre-packaged jquery snippets on how to create modal dialogs, and most client-side UI frameworks such as jQuery UI, YUI and Bootstrap have modal dialog functionality built-in. I'd recommend diving into those.
Try jquery plugins such as fancybox http://fancybox.net/
Basically, you need to attach an event listener to your new window to run the disableShadow() function in your webpage.
If you add this to your code I think it should work.
popup.unload(function() { disableShadow() });
Adapted From: Attach an onload handler on a window opened by Javascript
You should use the beforeUnload event of the window instance returned by the window.open() call, like this:
popup = window.open('relative_url', 'popup');
$(popup).bind('beforeunload', function() {
disableShadow();
});
Note that the URL must be on the same domain in order for the opener window to interact with the popup!
See the fiddle here: http://jsfiddle.net/hongaar/QCABh/
You can open a new window, and when it closes you can execute a function in the opener window.
I'll do a quick example by writing the script right into the new window, but you could also just include it in the HTML that is used for the new window if a link is supplied for the popup:
$("#popupBtn").on('click', openPopup); //using a button to open popup
function openPopup() {
$('#cover').fadeIn(400);
var left = ($(window).width()/2)-(200/2),
top = ($(window).height()/2)-(150/2),
pop = window.open ("", "popup", "width=400, height=300, top="+top+", left="+left),
html = '<!DOCTYPE html>';
html += '<head>';
html += '<title>My Popup</title>';
html += '<scr'+'ipt type="text/javascript">';
html += 'window.onbeforeunload = function() { window.opener.fadeoutBG(); }';
html += '</sc'+'ript>';
html += '</head>';
html += '<body bgcolor=black>';
html += '<center><b><h2 style="color: #fff;">Welcome to my most excellent popup!</h2></b></center><br><br>';
html += '<center><b><h2 style="color: #fff;">Now close me!</h2></b></center>';
html += '</body></html>';
pop.document.write(html);
}
window.fadeoutBG = function() { //function to call from popup
$('#cover').fadeOut(400);
}
Using a fixed cover that is faded in will also prevent any clicks on elements on the page, and you could even attach a click handler to the cover with pop.close() to close the popup if the cover is clicked, just like a modal would close if you clicked outside it.
One of the advantages of calling a function on the parent page from the popup is that values can be passed from the popup to the parent, and you can do a lot of stuff you otherwise could'nt.
FULLSCREEN_FIDDLE
FIDDLE
All you need is standard javascript function showModalDialog. Then your code will look like
var url = 'http://google.com';
showShadow();
var optionalReturnValue = showModalDialog(url);
//Following code will be executed AFTER you return (close) popup window/dialog
hideShadow();
UPDATE
As hongaar stated Opera does not like showModalDialog. And it does not fire on(before)unload when popup is closed either. To make workaround you need timer (window.setTimeout) to periodically check if window still exists. For further details look here
Why don't you just use jQuery UI? I know that you don't want another library but is rather extension of jQuery rather then another lib since it can live without it.
It have great deal of widget and every one of them can be changed,configured.
What is best that it can viewed with different themes, even you can create one with they're theme roller fast and easy, and it can be modularized. Just take what you need in current project.
Check this out:
http://jqueryui.com/dialog/#modal-form
It's really simple to use. With this you can open modal dialog with frame to different url. On close event you can do whatever you want.
Try ColorBox
its simple and easy to use
http://www.jacklmoore.com/colorbox
quick example:
<link rel="stylesheet" href="http://www.jacklmoore.com/colorbox/example1/colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://www.jacklmoore.com/colorbox/colorbox/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
$(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
});
</script>
<a class='iframe' href="http://google.com">Outside Webpage (Iframe)</a>
You can also try this out ...
http://fancyapps.com/fancybox/
Examples here
try http://thickbox.net/ in modal type, examples: http://thickbox.net/#examples
I've done this as well.
First off, some URLs simply WILL NOT WORK in an (iframe) modal window; I can't say if it'll work in the browser-supported native modal windows as I haven't tried this. Load google or facebook in an iframe, and see what happens.
Second, things like window onunload events don't always fire (as we've seen some people already).
The accepted answer version will also only work on a static page. Any reloading (even F5 on the page) will cause the shadow to hide. Since I can't comment on the accepted answer, I at least wanted this to be known for anyone else looking at these results.
I've taken a less technical approach to solving this problem in the past: polling.
http://jsfiddle.net/N8AqH/
<html>
<head>
<script type="text/javascript">
function openWindow(url)
{
var wnd = window.open(url);
var timer = null;
var poll = function()
{
if(wnd.closed) { alert('not opened'); clearInterval(timer); }
};
timer = setInterval(poll, 1000);
}
</script>
</head>
<body>
click me
</body>
</html>
See the link above for an example. I tested in IE, FF, and Chrome. My timer is every 1 second, but the effort on the browser is so low you could easily drop this down to 100 ms or so if you wanted it to feel more instant.
All you'd have to do in this example is, after calling window.open, call your "show shadow" function and instead of alerting when you close, call your "hide shadow" function and it should achieve what you're looking for.
Does the IFRAME's onload event fire when the HTML has fully downloaded, or only when all dependent elements load as well? (css/js/img)
The latter: <body onload= fires only when all dependent elements (css/js/img) have been loaded as well.
If you want to run JavaScript code when the HTML has been loaded, do this at the end of your HTML:
<script>alert('HTML loaded.')</script></body></html>
Here is a relevant e-mail thread about the difference between load and ready (jQuery supports both).
The above answer (using onload event) is correct, however in certain cases this seems to misbehave. Especially when dynamically generating a print template for web-content.
I try to print certain contents of a page by creating a dynamic iframe and printing it. If it contains images i cant get it to fire when the images are loaded. It always fires too soon when the images are still loading resulting in a incomplete print:
function printElement(jqElement){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write('<html><head></head><body onload="window.focus(); window.print()">');
printframe.document.write(jqElement[0].innerHTML);
printframe.document.write('</body></html>');
// printframe.document.body.onload = function(){
// printframe.focus();
// printframe.print();
// };
printframe.document.close();
// printframe.focus();
// printframe.print();
// printframe.document.body.onload = function()...
}
as you can see i tried out several methods to bind the onload handler... in any case it will fire too early. I know that because the browser print preview (google chrome) contains broken images. When I cancel the print and call that function again (images are now cached) the print preview is fine.
... fortunately i found a solution. not pretty but suitable. What it does that it scans the subtree for 'img' tags and checking the 'complete' state of those. if uncomplete it delays a recheck after 250ms.
function delayUntilImgComplete(element, func){
var images = element.find('img');
var complete = true;
$.each(images, function(index, image){
if (!image.complete) complete = false;
});
if (complete) func();
else setTimeout(function(){
delayUntilImgComplete(element, func);}
, 250);
}
function printElement(jqElement){
delayUntilImgComplete(jqElement, function(){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write(jqElement[0].innerHTML);
printframe.document.close();
printframe.focus();
printframe.print();
});
}
Just when the html loads, not the dependent elements. (or so I think).
To fire when the rest of the page loads do jQuery(window).load(function(){ or window.onload not document onready.
You can also check to see if an image element is loaded and there... if image . load-- etc.