set a value in .html file from an external .js file - javascript

i have a main.js that handles Key pressed. and i have a index.html that i want to recieve some variables from main.js and make decisions about it. for example i want to send a url from main.js to index.html .. i try this code in my main.js but not worked.
document.getElementById("url").value = "http://example.com";
in my index.html i have:
<form name="Params">
<input id="url" type="hidden" value="">
</form>
i just want to set value of my url input object from main.js.
any help?

It is important when did you call value assignment. It must be after DOM loaded. To do this you can try one of the followings.
Easiest way is just place your main.js script tag after /body close tag. it should work.
Assign the value in a function in main.js and call that function onload event.
--main.js
function assignValue()
{
document.getElementById("url").value = "http://example.com";
}
--index.html
<body onload="assignValue()" >

Your code looks fine to me but perhaps the code that triggers it isn't being fired. You haven't included the other part of your code that triggers the setting of the URL.

I'm guessing the reason it hasn't worked is because you're not waiting for DOM to initialize and the Web Browser has finished parsing the HTML.
The simplest 'fix' for this problem would be to hook into the window.onload callback in your main.js file:
// Wait for the DOM to finish loading.
var previousOnload = window.onload;
window.onload = function () {
// Execute any other `onload` function which may have been bound previously.
if (typeof previousOnload === 'function') {
previousOnload();
}
document.getElementById("url").value = "http://example.com";
});
However, it is preferred to listen for the DOM Ready event instead; if you're using jQuery then you can simply write:
// Wait for the DOM to initialize first.
$(function () {
document.getElementById("url").value = "http://example.com";
});
If you don't want to depend on jQuery then you could have a look into the super-lightweight DOMReady.js

Related

Write a js script in a div

I am trying to get a script from another website using jQuery then document.write it
here is my code
var url = "https://code.jquery.com/jquery-1.10.2.js";
var dam = $.getScript(url);
document.write(dam);
But this doesn't work!!
all what I get on the page is [object Object]
Can this be achieved without XHR?
jsfiddle
Don't use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document's content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don't use it.
Instead, you want to use modern DOM manipulation functions, so in jQuery, that's stuff like:
$(document.head).append($("<script>").attr("src", url));
where
$("<script>")
builds a new script element,
$(...).attr("src", url)
sets the "src" attribute to what you need it to be, and:
$(document.head).append(...)
or
$(document.body).append(...)
to get the script loaded into your document. If it's a plain script with src attribute, it can basically go anywhere, and if it's a script with text content that should run, you can only make that happen through document.head.
Although if it's just a script you need to load in and run, you can use getScript, but then you don't need to do anything else, it's just:
var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);
Done, jQuery will load the script and execute it. Nothing gets returned.
Of course, the code you're showing is loading jQuery, using jQuery, so that's kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:
<!doctype html>
<html>
<head>
...
</head>
<body>
...
<script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
with the script load at the end so the script load doesn't block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that's not even supported by Microsoft anymore, so you probably don't need to).
And finally, if we don't want to load the script, but we really just want its content, as plain text, there's only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that's:
$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
$(document.body).append($("div").text(data));
});
But you knew that already because that's been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?
executing the script on the page is not my goal!. I want to get the
script content and put it a div (USING JAVASCRIPT - NO XHR) , is that
possible ?
Try utilizing an <iframe> element
<div>
<iframe width="500" height="250" src="https://code.jquery.com/jquery-1.10.2.js">
</iframe>
</div>
jsfiddle http://jsfiddle.net/snygv469/3/
Make it easier... use my fiddle
http://jsfiddle.net/wwwfzya7/1/
I used javascript to create an HTML element
var url = "https://code.jquery.com/jquery-1.10.2.js";
var script = document.createElement("SCRIPT"); //creates: <script></script>
script.src = url; //creates: <script src="long_jquery_url.js"></script>
document.body.appendChild(script); //adds the javascript-object/html-element to the page.!!!
Use this way, it can fix your problems.
$.get( "https://code.jquery.com/jquery-1.10.2.js", function( data ) {
alert(data);
});
You can try adding
<script src="http://code.jquery.com/jquery-1.8.3.min.js" ></script>
Then an AJAX call, but it pulls data from CACHE. It looks like an AJAX but when <script> is added file goes in cache, then read from cache in the ajax. In cases where it is not stored in cache read it using normal AJAX.
jQuery.cachedScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "text",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
$(document).on('ready', function() {
// Usage
$.cachedScript("http://code.jquery.com/jquery-1.8.3.min.js").done(function(script, textStatus) {
console.log(script);
});
});
Normal Solution
If you are ready to use AJAX look at this fiddle
How to fetch content of remote file and paste it on your document and execute that js code
I guess you want to get content written on remote file and want to write that content in your HTML. to do this you can use load() function.
To do this follow the following steps:
1. Create a file index.html Write the following code in it:
<pre id="remote_script"></pre>
<script>
$(document).ready(function() {
//var url = "https://code.jquery.com/jquery-1.10.2.js";
var url = "remote_script.html";/* For testing*/
$('#remote_script').load(url,function(){
eval($('#remote_script').text()); /* to execute the code pasted in #remote_script*/
});
});
</script>
2. Create another file remote_script.html for testing write alert('a'); in it without any <script> tag and run the above code.

Cannot call external js function unless put it in html file

I have trouble to call external javascript function.
In my HTML:
<p> <a id="delete" href="/some/url/">Delete</a> </p>
I want to confirm before deletion. If I put the code in the html file, it works:
<script>
var test = document.getElementById("delete");
test.onclick = function popup(){return confirm("Are you sure?")};
</script>
However, if I put popup() function in external js file and include using "src=/path/to/external.js", the function cannot find, and no pop up window anymore.
I am pretty sure I type the correct path of external js, because I can open the js file in the html page source code. Also, if I use jquery.js file locally, it will not work, but if I use the jquery.js served by google CDN, it works. I am totally lost. Why this happens?
You need to be sure that when your JS is executed, the #delete element does exist in DOM.
To do so, you could simply include the .js file before </body>.
If you'd like to include it before </head>, your should fire the event binding after DOM ready (on DOMContentLoaded event, or later, window.onload), because JS is executed once it's downloaded, and at that time <body> is not rendered yet, document.getElementById("delete") would be null.
If you want to separate the event listener, you could try following code:
function popup(){return confirm("Are you sure?")}
test.onclick = popup; // Attention! Without brackets here.
Because the HTML element may not be on the page when the code is executed.
Use below:
window.onload=function(){
var test = document.getElementById("delete");
test.onclick = function popup(){return confirm("Are you sure?")};
};

jQuery get reference to calling script tag

I'm not sure the title of question is all right, as well as how much my question is valid.
Here is scenario:
// HTML
<script src="/script.js" data-app="app.js" />
// script.js
$(function () {
var script = // ???
});
Inside the js code, I want to get reference to original tag, the one who initialized the loading on "/script.js", so I'm able to check the data-app attribute.
Is that possible?
$('script').last().data('app');
Note that this may not be in a DOM ready block. The only place where you can access the current script tag is when it executes for the first time. An async callback such as the DOM ready event would not qualify for this. You can simply store the value in a variable though and then use it from inside your event:
(function() {
var app = $('script').last().data('app');
$(document).ready(function() {
// do stuff
});
})();
You can enumerate the scripts in document.scripts and recognize yours with its src property.
I don't think that there is a "proper" way to get your tag. However, in theory, when your script runs the corresponding tag should be the last one inserted into the document. So putting code like this into script.js works:
var child = document;
while (child && child.localName != "script")
child = child.lastChild;
if (child)
alert("My script tag: " + child);
You will need to run this code when the script loads and remember the script tag if you need it after the initial load.
document.scripts[document.scripts.length-1].src
i don't know what browser support it (IE and chrome, yes)

Position of window.onload in Javascript

I have a javascript code like this
<script type="text/javascript">
window.onload=myFunction;
</script>
Is there any difference in using the above snippet in the <head></head> tag and just before
</body> tag, as I would like to call my function after the page loads.
basically there's no pratical difference, but I recommend
to place that code at the bottom, since you need to use a script (blocking-rendering tag) it's better put it at the end of the document.
to avoid a destructive assignments like that: writing window.onload=myFunction you destroy other previous assignments to window.onload event (if any) so it's better something like
(function() {
var previousOnLoadIfAny = window.onload;
window.onload = function() {
if (typeof previousOnLoadIfAny === 'function') {
previousOnLoadIfAny();
}
yourfunction();
}
}());
Binding to window.onload will always run your function when the load event fires. This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to the DOMContentLoaded event or use a library like jQuery (e.g. $(function(){ myFunction() });).
The benefit about putting your function at the end of your <body> is that theoretically this means that the rest of your content has already loaded and you don’t need to bind your function to a load event. This sometimes works, but depends on the situation.
No, where you place that will not matter - anywhere in the document and it will trigger when the document and all external resources (images, scripts etc) has loaded.
Because onload triggers after all external resources one often want to use DOMContentLoaded instead which triggers when the HTML DOM is ready. Which will make for a page that is more responsive.

Javascript onload in HTML

I want to ask a question about the Javascript’s onload.
I’m writing a JSP page with the code <%# include file ="body.jsp". The included body.jsp contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload only usable on the body tag?
Onload can only be used for <body>, <img>, <script>, <iframe> tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>, <style>, <input type=image>, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>?
Inside your .jsp file
<script>
window.onload = function() {
alert("Hello!");
}
// or to execute some function
window.onload = myFunction; //notice no parenthesis
</script>
As the other guys already stated the onLoad event will not fire on a table. What you can do ist attaching the onLoad-handler to the body element (which will then fire, when the page is loaded) and manipulate the table by for example assigning an id to the table.
<body onload="function() { var table = document.getElementById("table-id"); ... }">
<table id="table-id"></table>
</body>
Are you using some javascript framework?
"onLoad" may be used on body- and frameset-tags.
To see some action you may use:
<body onload="function(){alert('This is an action!')}">
The easiest way i find is to use an external javascript file and jquery.
// Variables and functions you want to declare
var socket = io.connect();
// .....
// Function you want to run on load
$(function() {
$('#submit').click(function() {addUser();});
// ... any other functions you want to run on load
});
This is a code snippet from something that i was working on. The variable is declared before the code runs (It creates a web socket).
Then there is the jquery document selector ($) which runs on load and calls the init function to modify my html. I use it to call an anonymous function which runs right away.
You can throw a <script> tag right after your table with code. Once it gets to the script tag it would mean that the DOM for the table element above it has been loaded and can now be accessed in your script below it.
Note: The following below isn't applicable to the question but rather the other answers being given.
I recommend using the addEventListener function in javascript for adding the event. This makes sure that you are not overwriting or going to be overwritten by anyone else wanting to listen to the event.
Example
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener('load', function(event){ console.log("iframe Loaded", event); })

Categories

Resources