Access to every iframe child - javascript

I'm working with a client proyect which is working with lot's of iframes inside others.
The problem is that I want to add an addEventListener in all iframes automatically from the absolute parent document, an example schema would be this:
Document: iframe1, iframe2
Iframe1: iframe1.1, iframe1.2
Iframe1.1: iframe.1.1.1, iframe 1.1.2
I want to simulate something like this:
iframes[i].contentWindow.document.getElementsByTagName('iframe')[0].contentWindow.document.getElementsByTagName('iframe')[i]
I wrote this code, but I have an "undefined" error:
window.onload=function(){
eventoIframe(document,null,1);
}
var eventoIframe=function(target,prev_target,lvl){
console.log('Ejecuto funcion por '+lvl+' vez');
var iframes=target.getElementsByTagName('iframe');
if(lvl>2){
var iframes=prev_target.target.getElementsByTagName('iframe');
}
if(iframes.length>0){
for(var i=0;i<=iframes.length-1;i++){
var iframe=iframes[i].contentWindow;
iframe.addEventListener("click",function(event){
console.log('click on:', event.target)
},false);
eventoIframe(iframe.document,target,lvl+1);
}
}
}

Okay, I found the mistake, I don't know why I wanted to know the prev target hehe
The solution is
window.onload=function(){
eventoIframe(document);
}
var eventoIframe=function(target){
var iframes=target.getElementsByTagName('iframe');
if(iframes.length>0){
for(var i=0;i<=iframes.length-1;i++){
var iframe=iframes[i].contentWindow;
iframe.addEventListener("click",function(event){
//code to be execute on each iframe
},false);
eventoIframe(iframe.document);
}
}
}

Related

Handling State changes jQuery and History.js

Ok, so I need some insight into working with History.js and jQuery.
I have it set up and working (just not quite as you'd expect).
What I have is as follows:
$(function() {
var History = window.History;
if ( !History.enabled ) {
return false;
}
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('.ajax-link').click(function(e) {
e.preventDefault();
var url = this.href; //Tells us which page to load
var id = $(this).data('passid'); //Pass ID -- the ID in which to save in our state object
e.preventDefault();
console.log('url: '+url+' id:'+id);
History.pushState({ 'passid' : id }, $(this).text(), url);
});
History.Adapter.bind(window, 'statechange', function() {
console.log('state changed');
var State = History.getState(),
id = State.data.editid; //the ID passed, if available
$.get(State.url,
{ id: State.data.passid },
function(response) {
$('#subContent').fadeOut(200, function(){
var newContent = $(response).find('#subContent').html();
$('#subContent').html(newContent);
var scripts = $('script');
scripts.each(function(i) {
jQuery.globalEval($(this).text());
});
$('#subContent').fadeIn(200);
});
});
});
}); //end dom ready
It works as you'd expect as far as changing the url, passing the ID, changing the content. My question is this:
If I press back/forward on my browser a couple times the subContent section will basically fadeIn/fadeOut multiple times.
Any insight is appreciated. Thanks
===================================================
Edit: The problem was in my calling all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.
The problem was in my calling of all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.

Dynamically Adding HTML into an iFrame - Javascript

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.
Here's my code:
function createiFrame(min, max, key) {
console.log("Max-Width", max);
//CREATING A CLASS FOR THE IFRAME
var iframeClass = key + "-" + max;
//var path = window.location.pathname;
//var page = path.split("/").pop();
//ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
$(document).ready(function() {
$('<iframe>', {
width: max
}).addClass(iframeClass).prependTo('body');
});
var requiredHTML = document.getElementById('container').innerHTML;
console.log("RequiredHTML", requiredHTML);
//ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE
//IT STOPS WORKING
$('.' + iframeClass).ready(function() {
console.log("iFrame ready");
$('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
});
var $head = document.getElementsByTagName('head')[0].innerHTML;
$(document).ready(function() {
$('.' + iframeClass).contents().find('head').append($head);
});
}
EDIT
I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.
So new question;
How do I get the DOM ready?
check out this post:
addEventListener to iFrame
you need to use
$('#myIFrame').load(function(){
....
$('.' + iframeClass).ready(function() {
...
}
Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.
$(iframeClass document).ready(function() {
...
}
I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.

does not implement interface Element

First off, I've check this article and it doesn't quite seem to address the issue I'm having.
The code I'm using looks like this and for whatever reason, it refuses to run in Firefox and is giving an error of "Argument 1 of Window.getDefaultComputedStyle does not implement interface Element". This code is designed to switch tabs and can currently be found at testing.worldwidejamie.com.
Here is my full code:
$(document).ready(function(){
var content = undefined;
$('#tabs .tab-list li').each(function(){
$(this).on('click',function() {
// buttons
$(this).addClass('active').siblings().removeClass('active');
// content
if(content !== undefined){
content.hide();
}
var currentAttrValue = $("a", this).attr('href');
content = $(currentAttrValue);
content.show();
});
});
});
This works in the latest builds of Chrome, Safari, and IE but not in Firefox.
Thanks in advance for any help.
The code for the tabs works without fail. The problem is actually in your platform.js script. After checking the console output for the page via Firebug, the script breaks inside that script.
You can see here: http://jsfiddle.net/Au7EJ/3/ that your tabs.js script runs as you would expect. Only made one change to your code because there is no need to initialize 'content' with a value, so I changed it in the fiddle.
$(document).ready(function () {
var content; // just a declaration is enough here
$('#tabs .tab-list li').each(function () {
$(this).on('click', function () {
// buttons
$(this).addClass('active').siblings().removeClass('active');
// content
if (content !== undefined) {
content.hide();
}
var currentAttrValue = $("a", this).attr('href');
content = $(currentAttrValue);
content.show();
});
});
});
Hope this sheds some light on your problem!

How to determine if content in popup window is loaded

I need to set some contextData for a popup window from its parent. I try this:
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
w.contextData = contextData
//w.context data is null in the popup after the page loads - seems to get overwritten/deleted
});
});
It doesn't work, so my next thought, wait until content is loaded
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
w.onload = function() {
//Never Fires
w.contextData = contextData;
}
});
});
See this fiddle. My onload method never fires.
This works:
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
setTimeout(function(){
if(w.someVariableSetByThePageBeingLoaded) {
w.contextData = contextData;
}
else{
setTimeout(arguments.callee, 1);
}
}, 1);
});
});
But has obvious elegance problems (but is the current work around).
I know you can go the other way (have the popup call back to a method on the opener/parent, but this forces me to maintain some way of looking up context (and I have to pass the key to the context to the popup in the query string). The current method lets me capture the context in a closure, making my popup a much more reusable piece of code.
I am not trying to do this cross domain - both the parent and popup are in the same domain, although the parent is an iframe (hard to test with jsfiddle).
Suggestions?
If you are doing this with an iframe try it this way
HTML
<button id="clickme">Click Me</button>
<iframe id="framer"></iframe>
​
Javascript
$(function() {
$('#clickme').click(function() {
$("#framer").attr("src","http://jsfiddle.net");
$("#framer")[0].onload = function(){
alert('loaded');
};
});
});​
I updated your jsfiddle http://jsfiddle.net/HNvn3/2/
EDIT
Since the above is completely wrong this might point you in the right direction but it needs to be tried in the real environment to see if it works.
The global variable frames should be set and if you
window.open("http://jsfiddle.net","child_window");
frames["child_window"] might refer to the other window
I got javascript access errors when trying it in jsfiddle - so this might be the right track
EDIT2
Trying out on my local dev box I was able to make this work
var w = window.open("http://localhost");
w.window.onload = function(){
alert("here");
};
the alert() happened in the parent window

Javascript: Check if page contains a particular div

How do I check using javascript if the page I'm on contains a particular div... e.g turtles
if(document.getElementById("divid")!=null){
alert('Div exists')
}
if you have that div's id, you can do it that way:
var myDiv = document.getElementById( 'turtles' );
if ( myDiv ) {
//It exists
}
overwise, if it's a class, you'd better use a framework (jQuery here):
if ( $('.turtles').length > 0 ) {
//it exists
}
Like this:
<script type="text/javascript">
function CheckExists() {
var oDiv = document.getElementById("turtles");
if (oDiv) {
alert("exists");
}
else {
alert("does not exist");
}
}
</script>
The function must be located in bottom of page or called after page finished loading.
I'd just like to point out that document.contains is another way to do this.
document.contains is particularly useful if you have a web application whose components are rendered virtually before insertion into the DOM.

Categories

Resources