How to execute Javascript from external HTML - javascript

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'));
})

Related

Existing Functions aren't Functions?

So I'm working on a project. My functions are working fine, until all of a sudden I click a button that should run download(), but it doesn't. So I open the console, and see this:
TypeError: download is not a function
And I'm confused. I run download() from the console, and it works fine. So I think it might be an issue with onclick (my button has onclick="download()"), so I use JavaScript to add in the click event instead.
$("#download").onclick=download()
Note: $() is a custom jQuery-esque function without using the framework itself. It's worked on a lot of other uses at the same time as this problem.
But that doesn't work either. So I also try using
$("#download").addEventListener("click", download)
That yet again doesn't work. Both times it said that $() was null. So I go out on a limb, and try using
document.getElementById("download").onclick=download()
and the same with addEventListener(). But that gives me a very surprising error message:
TypeError: document.getElementById(...) is null
I've repeated all expressions in the console and found that they aren't null. I don't click the button until the page has been loaded very several seconds.
Here is the pertinent code:
function $(el){switch(el[0]){case"#":return document.getElementById(el.substring(1));break;case".":return document.getElementsByClassName(el.substring(1));break;default:return document.getElementsByTagName(el);break;}}
function download() {
alert("download() executed")
}
// Attempted Scripts:
//$("#download").onclick = download()
//$("#download").addEventListener("click", download)
//document.getElementById("download").onclick = download()
//document.getElementById("download").addEventListener("click", download)
<a class = "nav-link nohighlight" id = "download" onclick = "download()">Download</a>
It feels like my web browser is just trying to ensure I don't run the function. I've tested this on the latest Edge and Firefox. You can see my full page here.
Look at where your script tag is in your HTML: it's above the body. Scripts by default run immediately: when the HTML parser runs across them, it immediately executes the script before moving on to parse the rest of the HTML. So, at the time your script runs, none of your elements have been created yet - so, selecting any element will fail.
Either wrap your entire script in a DOMContentLoaded listener function:
document.addEventListener('DOMContentLoaded', () => {
// put your whole script here
});
Or give your script tag the defer attribute, which directs the parser to run it only once the document has been fully parsed:
<script src = "index.js" defer></script>

javascript onclick null in custom js file

I'm trying to simply detect clicking an A link to display an Alert box. Whenever I place the script inside the php file my a link is located, it works fine, but whenever I place it in my custom JS file, it doesn't detect it, and I get the error 'Uncaught TypeError : Cannot set property "onclick" of null'.
The link between the php page and custom js page is definitely working, as I have previous working code on the page. It simply wont detect my A link it its located in an external script.
HTML
<a id="ConfirmHolidayClose" href="#">
<img src="assets/img/close-button.png" alt="Holiday-request-close-button"
class="CloseButton" />
</a>
JAVASCRIPT
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
UPDATE - Forgot to mention sorry, my a link is nested inside div called 'ConfirmHoliday'.
I have JS code manipulating the ConfirmHoliday div inside my Custom JS, so it cant be loading after because it is finding its parent div perfectly well at the moment.
The javascript file runs before the element is created, thus it doesn't exist. To solve this, you have couple options:
1) Surround the code with a window.onload function
window.onload = function () {
// Your code here
};
2) Put it in a separate js file and add a defer property to the script tag.
<script src="yourScript.js" defer="defer"></script>
3) Put the script tag after the anchor tag
It's trying to access the ConfirmHolidayClose element before it exists maybe? Where is your JS loaded in your page? I'm guessing in your <head>
A few solutions:
1) Move your script to bottom of page just above </body>
2) wrap your JS in dom ready function, this ensures no JS will run until the DOM tree exists. Easiest with jQuery, example below...
jQuery example
$(function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Vanilla example
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});

Javascript adding <script> tag after page loads

Got a little problem here. Basically, I'm trying to add a script tag after the page loads.
This is what I am doing:
index.php:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getad()
{
$.post('assets/getad.php', "ad", function(response) {
response = response.replace('document.write','document.getElementById("ad").innerHTML = ');
eval(response);
console.log(response);
});
}
getad();
</script>
<div id="ad"></div>
</body>
</html>
getad.php:
<?php
echo file_get_contents("http://ads1.qadabra.com/t?id=a823aca3-9e3c-4ddd-a0cc-14b497cad85b&size=300x250");
?>
You can find a demo here: http://dev.cj.gy/game/
As you can see, the #ad div DOES get filled with the correct script tag, but it doesnt actually run, If I edit the page to include the script tag right at page load, it does run.
Yes, <script> tags cause execution when parsed as part of the main document; they don't execute from being written to innerHTML.
You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content and adding it to the document. This is what jQuery's getScript does.
However it wouldn't do you much good because the next script, that ads1.qadabra.com is document.writeing to the page, also itself calls document.write.
You could work your way around both of these calls at the client side (ie without getad.php), by assigning your own custom function to document.write that, instead of writing to the loading page, attempts to extract the source of the script tag passed to it, and load that in a DOM-created script element.
But in general these are scripts designed to work synchronously at document load time; anything you do to try to force them to run in a way they weren't intended to is likely to be fragile and stop working when the ad network change anything.
If you want to load a third-party ad without pausing the loading of the parent document, I suggest putting it in an iframe.

How can I remove a some javascript from my webpage?

With jquery.load() I'm loading some html into my page from a file which also contains javascript functions.
later I try to remove the html and the javascript using jquery.empty but it seems once the script is parsed by the browser I can't get rid of it, so I'm looking for suggestions on how to do this.
Below is the test source:
index.html
<head>
<script src="//code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script>
$(function(){
$('#loadEmbScrpt').click(function(){
$('#embDiv').load('http://maccyd10.hostoi.com/test.html');
});
$('#remEmbScrpt').click(function(){
$('#embDiv').empty();
});
});
<body>
<div id="embDiv"></div>
<div id="output"></div>
<input type="button" id="loadEmbScrpt" value="embed script into page"/>
<input type="button" id="remEmbScrpt" value="remove embedded script from page"/>
<input type="button" id="testButton" value="run embedded script test function"/>
</body>
test.html
<script>
$('#testButton').on('click',function(){
$('#output').append("<p>test</p>");
});
</script>
And here is a link to the above in action (I could not post this to jsfiddle due to XSS protection).
http://maccyd10.hostoi.com
Have a play with this http://jsfiddle.net/6eWRQ/
As others have alluded to, the DOM and the Javascript VM are two separate systems within the browser.
The DOM is the browser's internal model of the HTML document to be rendered. It deals with HTML elements such as <script> and their position within the HTML document.
The Javascript VM deals with javascript code - it deals with running any Javascript code within <script> tags or pulled in from external js files.
it seems once the script is parsed by the browser I can't get rid of it
You can of course remove the <script> element from the DOM - but after the browser has parsed it this will have zero effect on the javascript VM - because then the javascript code inside the tag it has already been consumed and executed by the VM. Once the code has run, it cannot be un-run.
In the case of the example jsfiddle this is even clearer - removing a <script> element containing a function doesn't mean you can't call that function any more, once the code inside the <script> has already been executed by the VM. The VM has its own internal model of the function and changes to the original code in the DOM after it has been executed are simply irrelevant to it.
Removing the containing <script> element from the DOM using javascript is effectively pointless in this situation - it's just redundant. The DOM rendering engine has no use for it because it's not a visual element, and the javascript VM has no use for it because it's already-processed input.
To do what you want you should remove the #remEmbScrpt button, and instead use the following to undo the binding performed by the loaded script:
$('#testButton').off('click');
As has been mentioned in the comments, you can't get rid of javascript once it has been loaded.
With that being said, if you wish to undo the changes made by the script you posted above, the .off() function will unbind all attached to a handler (so if any other events are attached to click, they will be removed to).
e.g. the following will unbind the functions from the click events on $('#loadEmbScrpt') and $('#remEmbScrpt') :
$('#loadEmbScrpt').off('click');
$('#remEmbScrpt').off('click');
or if you want it all in one line:
$('#loadEmbScrpt,#remEmbScrpt').off('click');
Let me know if that solves your problem

call function to highlight code

Please see the the following http://valogiannis.com/recent/ .I have a webpage and when user click XHTML code a div with id result loads the contents of a webpage (in this case codes/advocasys.html). In fact what I wish to do is to highlight the html code. I have link the necessary css/js. I use the SyntaxHighlighter 3.0.83. This highlighter needs to call the SyntaxHighlighter.all() after the <pre> tag (more info here). If I have the html code in the same page which I want to highlight works nice, but I cannot make it to work, when the script loads the external page advocasys.html. I tried to put the
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
in the bottom of the advocasys.html, but It didn't work. How can I make it work?
Thanks in advance.
The .all() call attaches an event handler to window.load which already happened, instead use .highlight(), like this:
SyntaxHighlighter.highlight();
You need to call SyntaxHiglighter in the callback function after the data is returned:
$('#myLink').click(function(){
$('#result').load('codes/advocasys.html', function() {
$('#result').show();
$('.scroll-pane').jScrollPane();
SyntaxHighlighter.highlight();
});
return false;
});

Categories