I have a javascript that executes within a element like : <a href="javascript:doSomething();"> but it doesn't execute on window.load , anyone knows why does that happen ?
With the example above doSomething() will only be called when the user clicks on the anchor. If you want it to execute on window.load you need to put the code in the head. i.e.
<script type="text/javascript">
window.onload = doSomething;
</script>
Also, if you're going to be using the onload event a lot I would personally recommend getting jQuery and using it's 'on DOM ready' event. This way your javascript will appear seamless to the end-user and won't have a flickering effect.
Have you tried writing <body onload="doSomething();">?
Assuming you did all the other suggestions, there is always a chance that someone later in the code (after your either <body onload=... or window.onload = ...) did exactly the same, and has overriden you.
If it happens to be the case (low chance) the solution to support both of your onload hooks, is window.attachEvent("onload", doSomething)
If I understand your problem correctly, you want to set an attribute in an element, calculating it dynamically via javascript, so that when the page is loaded your link points to the return value of "doSomething()".
For that you can use javascript's DOM manipulation utility functions.
In your case something like:
<a id="myLink">my anchor</a>
...
<script type="text/javascript">
getElementById('myLink').href = doSomething();
</script>
Related
I have this ajax call that's suppose to run when a key is pressed on a specific textbox. Once in the call, it runs a function that fires an alert. But, its doesn't work. Maybe it's cause I wrote the call using an old forum post as reference. Assume, I called the jquery library cause on my test I did but I didn't post it here.
This is what I've tried so far:
<script>
$("#<% =tb.ClientID%>").keydown
(
function ()
{
debugger; alert("hello");
}
);
</script>
<body>
<asp:TextBox Id = "tb" runat = "server"/>
</body>
I'm new to these kind of calls. I'm very familiar with js functions, but I've never done this. Any explanations and suggestions, would be greatly appreciated.
HTML is processed line by line. So when it processes the contents of that script tag, it hasn't yet processed anything further down, such as the body tag or its contents.
Inside the script, you're running $("#<% =tb.ClientID%>"). It'll try to find an element by its ID, but since the body hasn't been processed yet, it will yield no results. With no results, it has nothing on which to set the listener for .keydown.
It's in cases like these that using jQuery's $(document).ready function or its equivalents becomes incredibly important and crucial to the code. $(document).ready accepts a function, and it will wait until the DOM is fully loaded before executing that code. So putting $("#<% =tb.ClientID%>").keydown.... inside of a $(document).ready will ensure that the element has a chance to enter the DOM before the .keydown listener is attached to it.
You can find the docs for $(document).ready() here.
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();
});
Here is the circumstance:
I have 2 pages:
1 x html page
1 x external Javascript
Now in the html page, there will be internal Javascript coding to allow the placement of the window.onload, and other page specific methods/functions.
But, in the external Javascript I want certain things to be done before the window.onload event is triggered. This is to allow customized components to be initialized first.
Is there a way to ensure initialization to occur in the external Javascript before the window.onload event is triggered?
The reason I have asked this, is to attempt to make reusable code (build once - use all over), to which the external script must check that it is in 'order/check' before the Javascript in the main html/jsp/asp/PHP page takes over. And also I am not looking for a solution in jQuery #_#
Here are some of the links on Stack Overflow I have browsed through for a solution:
Javascript - How to detect if document has loaded (IE 7/Firefox 3)
How to check if page has FULLY loaded(scripts and all)?
Execute Javascript When Page Has Fully Loaded
Can someone help or direct me to a solution, your help will be muchness of greatness appreciated.
[updated response - 19 November 2012]
Hi all, thanks for you advice and suggested solutions, they have all been useful in the search and testing for a viable solution.
Though I feel that I am not 100% satisfied with my own results, I know your advice and help has moved me closer to a solution, and may indeed aid others in a similar situation.
Here is what I have come up with:
test_page.html
<html>
<head>
<title></title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript" src="test_script_1.js"></script>
<script type="text/javascript" src="test_script_2.js"></script>
<script type="text/javascript">
window.onload = function() {
document.getElementById("div_1").innerHTML = "window.onload complete!";
}
</script>
<style type="text/css">
div {
border:thin solid #000000;
width:500px;
}
</head>
<body>
<div id="div_1"></div>
<br/><br/>
<div id="div_2"></div>
<br/><br/>
<div id="div_3"></div>
</body>
</html>
loader.js
var Loader = {
methods_arr : [],
init_Loader : new function() {
document.onreadystatechange = function(e) {
if (document.readyState == "complete") {
for (var i = 0; i < Loader.methods_arr.length; i++) {
Loader.method_arr[i]();
}
}
}
},
load : function(method) {
Loader.methods_arr.push(method);
}
}
test_script_1.js
Loader.load(function(){initTestScript1();});
function initTestScript1() {
document.getElementById("div_1").innerHTML = "Test Script 1 Initialized!";
}
test_script_2.js
Loader.load(function(){initTestScript2();});
function initTestScript2() {
document.getElementById("div_2").innerHTML = "Test Script 2 Initialized!";
}
This will ensure that scripts are invoked before invocation of the window.onload event handler, but also ensuring that the document is rendered first.
What do you think of this possible solution?
Thanking you all again for the aid and help :D
Basically, you're looking for this:
document.onreadystatechange = function(e)
{
if (document.readyState === 'complete')
{
//dom is ready, window.onload fires later
}
};
window.onload = function(e)
{
//document.readyState will be complete, it's one of the requirements for the window.onload event to be fired
//do stuff for when everything is loaded
};
see MDN for more details.
Do keep in mind that the DOM might be loaded here, but that doesn't mean that the external js file has been loaded, so you might not have access to all the functions/objects that are defined in that script. If you want to check for that, you'll have to use window.onload, to ensure that all external resources have been loaded, too.
So, basically, in your external script, you'll be needing 2 event handlers: one for the readystatechange, which does what you need to be done on DOMready, and a window.onload, which will, by definition, be fired after the document is ready. (this checks if the page is fully loaded).
Just so you know, in IE<9 window.onload causes a memory leak (because the DOM and the JScript engine are two separate entities, the window object never gets unloaded fully, and the listener isn't GC'ed). There is a way to fix this, which I've posted here, it's quite verbose, though, but just so you know...
If you want something to be done right away without waiting for any event then you can just do it in the JavaScript - you don't have to do anything for your code to run right away, just don't do anything that would make your code wait. So it's actually easier than waiting for events.
For example if you have this HTML:
<div id=one></div>
<script src="your-script.js"></script>
<div id=two></div>
then whatever code is in your-script.js will be run after the div with id=one but before the div with id=two is parsed. Just don't register event callbacks but do what you need right away in your JavaScript.
javascript runs from top to bottom. this means.. if you include your external javascript before your internal javascript it would simply run before the internal javascript runs.
It is also possible to use the DOMContentLoaded event of the Window interface.
addEventListener("DOMContentLoaded", function() {
// Your code goes here
});
The above code is actually adding the event listener to the window object, though it's not qualified as window.addEventListener because the window object is also the global scope of JavaScript code in webpages.
DOMContentLoaded happens before load, when images and other parts of the webpage aren't still fully loaded. However, all the elements added to the DOM within the initial call stack are guaranteed to be already added to their parents prior to this event.
You can find the official documentation here.
What is the best unobtrusive way of invoking something after the page is being loaded in plain JavaScript? Of course in jQuery I would use:
$(document).ready(function(){...});
but I am not sure about the most reliable approach in plain js.
Clearly
window.onload = ...
is not proper solution, because it would overwrite previous declaration.
What I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like:
window.onload = function(divId){
var div = document.getElementById(divId);
div.innerHTML = "<iframe src='someUrl' .. >";
}
EDIT:
Apologies for not including all necessary details.
The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code. That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change URL of an iframe or I would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.
//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );
//For IE:
document.attachEvent( "onreadystatechange", someFunction);
`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.
See:
https://developer.mozilla.org/en/DOM/element.addEventListener
Also definitly worth looking at how jQuery does it:
http://code.jquery.com/jquery-1.7.js Search for bindReady.
Use window.addEventListener and the events load or DOMContentLoaded:
window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});
object.addEventListener('event',callback) will insert an event listener into a queue for that specific object event. See https://developer.mozilla.org/en/DOM/element.addEventListener for further information.
For IE5-8 use window.attachEvent('event',callback), see http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. You can build yourself a little helper function:
function addEventHandler(object,szEvent,cbCallback){
if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
return false;
if(!!object.addEventListener){ // for IE9+
return object.addEventListener(szEvent,cbCallback);
}
if(!!object.attachEvent){ // for IE <=8
return object.attachEvent(szEvent,cbCallback);
}
return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});
Note that DOMContentLoaded isn't defined in IE lesser 9. If you don't know your recipient's browser use the event load.
Just put your script include at the very end of the document, immediately before or after the ending </body> tag, e.g.:
(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>
All of the markup above the script will be accessible via the usual DOM methods (reference). Obviously, not all ancillary resources (images and such) will be fully loaded yet, but presumably that's why you want to avoid the window load event (it happens so late).
The only real purpose of ready-style events is if you don't control where the script gets included (e.g., libraries) or you need to have something execute prior to the page load and something else after the page load, and you want to avoid having two HTTP requests (e.g., for two different scripts, one before load and one after).
I'd like to build onmouseover directly into a javascript block. I can do it within a hyperlink but I need to do it in the actual script section for the code im writing. Can I do object.onMouseOver()? Or is there another way to do it?
So for example I'd like
<script>
something i can put in here that will make on mouseover work on a specific object
</script>
Yes. :)
<span onmouseover="alert('Hi there')">Hi there</span>
Do you mean like that?
edited to add:
Ah I see so like this?
<span id="span1">Hi there</span>
<script>
document.getElementById('span1').onmouseover = function() {
alert('Hi there');
}
</script>
You bind events to HTML elements not javascript blocks. If you are talking about binding events to elements using script, yes you can do it. You can use addEventListener to bind events.
document.getElementById("eleid").addEventListener("mouseOver", myEventMethod, false);
Yes you can so if you have a link somewhere in the page that you want to fire the hover for you can use the following.
http://jsbin.com/asoma4/edit
EDIT: I should add that the attached is just an ugly example to demonstrate that what you want to do can be done. I would look into popular js libraries (jquery, prototype, etc..) to clean this up a lot and make it easier.
You can use addEventListener in Firefox/Chrome/etc. and attachEvent in IE. See this page.
For example,
<div id="cool">Click here!</div>
<script>
function divClicked()
{
// Do some stuff
}
var theDiv = document.getElementById("cool");
if(theDiv.attachEvent)
{
// IE
theDiv.attachEvent('onclick', divClicked);
}
else
{
// Other browsers
theDiv.addEventListener('click', divClicked, false);
}
</script>
If you want to avoid having to write all that code, you can use a JavaScript library (jQuery, Prototype, etc.) to simply your code.