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.
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 have an iframe with video player and I want to disable some it's features. Since there is no documentation, I've just created a div, put it on top of the iframe and when I check coordinates of users clicks I decide whether I need to transmit this click to this iframe or not. Here's how it looks like:
<iframe
src="http://website.com/embed/dfgdgssg"
style="position: absolute; top: 100px; left: 350px;"></iframe>
<div id="hideme"></div>
<script>
$('iframe').load(function() {
var iframe = $(this);
var hideme = $('#hideme');
hideme.width(iframe.width());
hideme.height(iframe.height());
hideme.css('left', iframe.position().left);
hideme.css('top', iframe.position().top);
hideme.on("click", function(event){
iframe.trigger(event);
});
});
</script>
Using console.log() I can see that event click for #hideme is executed, but nothing changes for the iframe though.
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.
After clicking a link with a common href (local page or web-site)
and the href is successfully loaded, both FF2 and IE7 will display
the link with a:visited styling.
For links with href="javascript:anyfunc()", IE7 works as above
while FF2 does not display a:visited styling. No change with any
DOCTYPE.
Q: Is either behaviour with JS links and :visited considered correct?
Q: Does FF2 leave anchor state unchanged after clicking a JS link?
Q: Without having to attach an onClick handler or modify classes/style
with JS, is there a concise way to tell FF2 to use :visted
styling independent of whether href is another page or a JS link?
Example follows:
<html>
<head>
<style>
div.links { font-size: 18px; }
div.links a { color: black; text-decoration: none; }
div.links a:visited { background-color: purple; color: yellow; }
div.links a:hover { background-color: yellow; color: black; }
</style>
<script>
function tfunc(info) { alert("tfunc: info = " + info) }
</script>
</head>
<body>
<div class="links">
JS Link 1<br>
JS Link 2<br>
Common href, google
</div>
</body>
</html>
It would be difficult to style these sorts of links... whilst they may have the same href, they could potentially do anything through JS (which may make it seem that visiting it would not).
Is there a way to link to something such as a HTML page and attach event handlers to the link (and return false to stop the link clicking through)? And if the links are in fact JS hooks, I would use an element such as a <button> and style it accordingly... remember to add cursor: pointer so the end user knows it is clickable.
Using inline javascript:function(something) in a href is bad practice. Try unobtrusive event handlers.
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective!
Here's my take:
Q: Is either behaviour with JS links and :visited considered correct?
The purpose of a link is to retrieve a resource. If your link doesn't go anywhere, what are you "visiting"? The behavior is correct from this perspective in my opinion.
Q: Does FF2 leave anchor state unchanged after clicking a JS link?
It seems as though it doesn't change the state of the link to :visited unless it points to an element in the page (which means the link points to the current page which is implicitly visited) or to another resource which as already been accessed.
Q: Without having to attach an onClick handler or modify classes/style with JS, is there a concise way to tell FF2 to use :visted styling independent of whether href is another page or a JS link?
I don't think so. You can probably get the visited effect if you point the href of the link to "#" and use the onclick handler for your JavaScript needs.
I have encountered the issue I believe this question is asking. Consider this simple example:
style sheet:
#homebox { display: none;}
#contactbox { display: none; }
html:
<a id="#home"></a>
Show Home
<div id="homebox">Your home</div>
<a id="#contact onclick="return showHideDiv(this);"></a>
<div id="contactbox">Contact Info</div>
script:
function showHideDiv(elem) {
if( elem.style.display && elem.style.display == "none"; ) elem.style.display = "block";
else if( elem.style.display && elem.style.display == "block"; ) elem.style.display = "none";
return true;
}
Although not the most beautiful code, it points out some issues which can develop when using javascript onlick within a href. The reason you might want to do something like this, is to create dynamic content changes without reload which show a visited style. The a links would be handier than buttons, so the visited status of the links is maintained, even though internal. However, I have noticed some issues with browsers triggering visited status on internal links, let alone internal links with javascript onclick event handlers. A button would require coding a function to control visited styles.
I agree with Alex, a link should be a link to something, not a JS trigger - a button would much more effective here.
If you do want to attach some JS function to a link, you should definitely use some unobtrusive JS to attach that function to the click event.
EG using jQuery:
$("#myLinkID").click(function () {
//function stuff
});