Running Javascript inside Iframe without affecting the main page - javascript

I have to add an iframe in my webpage and inside that load a widget with the use of javascript.
I have done a lot of research on this and found that this implementation affects the main page as well probably because of the other css and scripts the widget might load.
So basically in a nutshell I have only one question-
What is the best way to make an iframe element and attatch a script to that so that it doesn't affect the whole page.
The different pieces of code I have used till now,
iframe=$('<iframe>');
iframe[0].appendChild('<scr' + 'ipt type="text/javascript" src="https://somecode.com/code/js-widget/orderingWidget.js"></scr' + 'ipt>');
Error:iframe[0] is undefined.
The other one
var previewDoc = window.frames[0].document;
previewDoc.write("<!DOCTYPE html>");
previewDoc.write("<html>");
previewDoc.write("<head>");
previewDoc.write("<style type='text/css'></style>");
previewDoc.write("<script type='text/javascript' src='https://somecode.com/code/js-widget/orderingWidget.js'");
previewDoc.write("</head>");
previewDoc.write("<body>");
previewDoc.write("test");
previewDoc.write("</body>");
previewDoc.write("</html>");
previewDoc.close();
Error: window.frames[0] is undefined.
And this one, where iframe is already created using jquery and assigned id=myiframe,
$(function() {
$iframe = $('#myiframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
});
Error:Affects the whole page and triggered through console and not actually the function being called.
Thanks in advance.
PS:I have used content.document and content.window.document, both return undefined.

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

start script as soon as the page opens

I have a jquery script that changes an element to fixed when the page is scrolled.
The problem is that the script won't work until the page is fully loaded, and it can take some time
Is there a way to start the script as soon as the user enters the page, without having to wait until it finishes loading ?
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var menuOffset = $('#ribbonmenu')[0].offsetTop;
$(document).bind('ready scroll', function() {
var docScroll = $(document).scrollTop();
if (docScroll >= menuOffset) {
$('#ribbonmenu').addClass('fixed');
} else {
$('#ribbonmenu').removeClass('fixed');
}
});
});//]]>
</script>
Yeah, put it outside:
$(window).load(function() {
That will answer your question about wanting your script to run instantly, however there are issues beyond just moving it outside the load function.
As Marc B said, your script which calls upon an HTML element will not run if it is outside your load function because for a very, very, small time period the HTML hasn't loaded and your script will not see your HTML.
This will cause an error thus making your script not work as intended. Therefore you should keep it inside the load function and instead look for alternative ways to speed up your server/script.
Rather than using $(window).load(
you could try using $( document ).ready(.
It will load sooner, but as others have mentioned, there isn't a way to get it to load instantaneously and still work. This is because future elements will not have loaded yet.

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

Reload? Javascript after Jquery .live/.load

I wanted to load some fragments of external content inside a div, through a menu.
Found "load" and "live", found a tutorial used it = success!
Except, like what's explicit in the documentation, it doesn't load JavaScript.
The thing is, the destination page already loads, inside the header, that same JavaScript, 'cause Wordpress loads it in every page. In this particular page, I'm only using the plugin (nextgen gallery) through the jQuery AJAX call.
So, what I believe is my problem is that I somehow need to alert/reload the JavaScript, right?
And how can I do this?
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
// ajax pagination
jQuery('#naveg a').live('click', function(){ // if not using wp-page-numbers, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('#fora').html('<div class="loading"><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('#fora').load(link+' #dentro')
return false;
});
}); // end ready function
</script>
PS: I've substituted "live" with "on" but didn't work either.
I'm not sure if I understand... your load() command is puling in some Javascript that you want executed? I'm not sure if you can do that. But if you just need to call some JS upon load() completion, you can pass it a function like so:
jQuery('#fora').load(link+' #dentro', function() {
console.log("load completed");
// JS code to be executed...
});
If you want to execute Javascript code included in the loaded page (the page you retrieve via .load()), than you have to use the url-parameter without the "suffixed selector expression". See jQuery documentation for (.load()):
Note: When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is however called with a selector expression appended to the
URL, the scripts are stripped out prior to the DOM being updated,
which is why they are never executed. An example of both cases can be
seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
However in this case, script blocks in the document being loaded into
#b are stripped out prior to being executed:
$('#b').load('article.html #target');
I think that's your problem (although I have no solution for you, sorry).
Proposal: Maybe you can load the whole page (including the Scripts) and remove (or hide) the parts you don't need?
Cheers.

How to add Javascript code using jQuery and setTimeout()

I have some tracking code that the provider (WebTraxs) says should be placed at the bottom of the tag. The problem is that this same code is causing everything on the page (including my jQuery code) to run AFTER the WebTraxs is executed. This execution sometimes takes long enough where images rollovers, etc aren't working because the user is mousing over images before WebTraxs has finished.
Therefore, I'm trying to add the needed tags (from WebTraxs) to the body after the page is loading in the document ready handler, using the following:
setTimeout(function(){
var daScript = '<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" />';
var daOtherScript = '<noscript><img alt="" src="http://db2.webtraxs.com/webtraxs.php?id=company&st=img" />';
$('body').append(daScript);
$('body').append(daOtherScript);
},
5000);
I have two problems with the above:
In Firefox, after 5 seconds, it page goes completely blank.
In IE, there's no errors thrown, but normally you can see the WebTraxs code trying to load a tracking image in the status bar. This is not occurring with the above code.
Is there a better way to accomplish my objective here? I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
Why don't you use the .getScript function:
setTimeout(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
},
5000);
What it's really curious about your code is that you add a <noscript> tag using JavaScript... it does not make any sense. If the user does not have JavaScript the setTimeout won't be fired, thus it <noscript> content won't be displayed.
I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
In that case, you just have to do this:
$(document).ready(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
});
You don't have to use jQuery's DOMReady event handler. The reason people use DOMReady is that it allows the full DOM to load before firing up scripts that manipulate the page. If you call your scripts too early, parts of your page may not be accessible -- for example, if you call them before <div id="footer">...</div>, they won't be able to see $('div#footer') because it's not been pulled into the DOM yet. And that's great, except that your DOMReady methods will always execute after any in-page scripts have executed first. That's why your webtrax code is getting executed first.
But you can get the same benefits of DOMReady and still control the order of execution by calling your page scripts at the end of your document, when there's nothing left but HTML closing tags. They will be executed in the order they appear.
So try this instead:
<html>
<head>
<script type="text/javascript" src="myPageScripts.js"></script>
</head>
<body>
<div id="pagesection1"></div>
<div id="pagesection2"></div>
<div id="pagesection3"></div>
<!--NO MORE CONTENT BELOW THIS LINE-->
<script type="text/javascript">//<![CDATA[
runMyPageInitializerScripts();
//]]></script>
<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" ></script>
</body>
</html>
In this script, runMyPageInitializerScripts() would still have complete access to #pagesection1, pagesection2 and pagesection3, but would not see the final script tag. So the page isn't in exactly the same condition as when DOMReady is fired, but for most scripts usually there is no downside.
<script> tags cannot use a shortcut like <script/>.
You have to use <script></script>
Anyways, I don't understand where the difference is on executing those scripts on DOMready or after a specific amount of time. If it blocks the UI it will do the same after 5 seconds no?
You are missing the closing </script> and </noscript> tags.
If you want to keep the <script> tag you may need to escape it (not sure if this persists on newest browsers, but as far as i remember you can't have <script> tags inside a script tag), take old google analytics code as example:
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
Splitting the script tag also works:
document.write("<scr"+"ipt src='somescript.js'></sc"+"ript>");
But since you're using jQuery, .getScript() is your best option.

Categories

Resources