Accessing external JS variable from inline html page? - javascript

How do you access the variable from an external JavaScript within a HTML page?
In my external JavaScript file(init.js), I created a variable call:
var myMessage="Hello World";
And in my HTML page which has init.js included but when I try alerting it:
alert(myMessage);
It gives me an error.
Sample code here

your codepen sample does not include the code as an external file but internally so that is an issue, but generally you need to wait for the page and all elements to finish loading.
The example bellow will wait 1000ms or 1sec and then you'll see that the alert will show the variable.
<div>
Body content
</div>
<script>
setTimeout(function() {
alert(myMessage);
},1000);
</script>
The better way is of course to use jQuery's
$('document').ready(function(){ });
instead of a timer as you can't be sure 1 second is enough. the connection might be poor and it could take more for all the pages to load.
If you dont want to use jQuery there are vanilla JS ways to do it as well.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

You can call external js variable through making
var init={
myMessage="Hello World";
}
call your html code
alert(init.myMessage);

Related

Defer execution of <Script> tag until after jQuery .load completes

I'm trying to 'include' some generated HTML code on my page with jQuery load (injecting it into #loadhead div):
<script>
$("#loadhead").load("head.php");
</script>
<script defer>
... rest of the code
</script>
I want the second part of the script to load only after head.php is done loading. I tried to enforce execution of the second script tag with defer, but it deson't seem to work - still, once in a while, head.php doesn't manage to load before the rest of the code. What can I do to ensure it is always loaded completely? It generates some JavaScript values that are used by the 'defer' script.
Two options for you:
1. Use a function you call from load's callback
Put your second script's code in a function, so it's loaded but not run, and then call that function from load's success callback.
Example:
<script>
$("#loadhead").load("head.php", otherStuff);
function otherStuff() {
// ...
}
</script>
(I didn't see any reason they should be in separate script tags, so they aren't.)
I'd probably put that all in a .js file and link it rather than having script embedded in the HTML inline.
2. Load the script when load is done
Don't include the second script tag at all; load the script later in the load success callback, either using $.getScript or appending a script element.
Example:
<script>
$("#loadhead").load("head.php", function() {
$.getScript("otherstuff.js");
});
</script>
(I didn't see any reason they should be in separate script tags, so they aren't.)
I'd very much go with Option #1, to avoid unnecessary delays.

Loading script statically and run when it is loaded

I am placing a script as the following:
<script src="https://cdn.jsdelivr.net/blabla.js" type="text/javascript" id="the_script"></script>
In jquery I can:
$("#the_script").ready(function(){
alert("loaded")
});
But I am not using JQuery.
What is the equivalent in vanilla js (native).
here is an example in jsfiddle http://jsfiddle.net/bmhm65vm/
Running a script as soon as a browser loads (meaning before anything else)
requires you to put the code you want to execute first into the following function:
window.onload = function(){
//Your Code Here.
};
The block of code inside of the window.onload function will be run FIRST.
You can always use onload like in this fiddle http://jsfiddle.net/est4dsav/
Here you have all the native options: http://www.w3schools.com/jsref/event_onload.asp

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

How to execute Javascript from external HTML

If I have a button that executes the code
$('#main').load('welcome.html');
and in welcome.html I have a button that executes the code
$('#main').load('otherpage.html');
the Javascript isn't executed, regardless of whether that function is on the parent file's HTML code or the child's.
How can I get a Javascript function to work from externally loaded HTML files?
EDIT
Here's a bit more of a sample...
Homepage:
<body>
<div id="main"></div>
</body>
<script>
document.onLoad(){
$('#main').load('welcome.html');
}
function show(file){
$('#main').load(file+'.html');
}
</script>
welcome.html page:
Test
...however when the Test button is clicked, test.html is not loaded into the Main div.
EDIT 2
Here is what the current state is and what the issue is - exactly.
I've uploaded the bones of the code to PasteBin.
When the 'grid' button is clicked, the content changes and the footer changes.
However, the footer, which has URLs based on Javascript, comes up with the error:
Uncaught SyntaxError: Unexpected token ILLEGAL
...when trying to access the 1i.html page.
There's a difference between test the variable and 'test' the string:
Test
Probably should be:
Test
It is important to understand that when loading script into page via AJAX that the main page has already gone through document.ready . Thus, any code you load will fire immediately.
If the code you load precedes the html it references, it will not find that html when it fires.
Placing the code after the html in remote page will resolve this issue
Check jQuery.live() and jQuery.on().
Maybe your eventhandler is wrong. When you import new markup via load() or ajax(), you have to initialize the handlers from new document. The easiest way is using jQuery.on or jQuery.live() instead of jQuery.click().
$('MYBUTTON').live('click', function(){
$('#main').load('your_url.html')
})
or use the callbackfunction to (re-)initialize the buttons event.
A better solution is this: Just add the target_url to buttons rel attribute...
<button rel="YOUR_URL.html">Open Page</button>
$('button[rel]').live('click', function(){
$('#main').load($(this).attr('rel'));
})

How to determine when a page modified with JS is done loading?

I have a very bare HTML page that loads two JS files. One of these JS files then goes and loads a varying amount of content into the page.
I'm trying to get the equivalent of window.onload for this extra content. Obviously, window.onload actually fires very quickly, when the page is done loading the two JS files.
Any ideas? I know I can go and attach onload events to every image/script/etc on the page, but would rather not...
EDIT. If the callback won't help .load should do the job. I've added it to the example.
In this case you need a call back. Are you using a JavaScript library? if so what library?
In your existing code, after you append to the document you need to call a function that can execute the next bit of code.
something like this.
//FILE 1
$(function () {
$('body').append(someHTMLOrDOMNodes);
//I don't know what your second script does, but you should name this callback something relevant.
$('#idOfNewContent').load(function() {
callback();
});
});
//FILE 2
function callback() {
//next bit of code.
}

Categories