Javascript using onload twice in html file and external script file - javascript

I have an external JS file that I load into my HTML
<script type="text/javascript" src="../js/busy.js"></script>
The script file itself looks like this:
window.onload = setupFunc;
function setupFunc() {
document.getElementsByTagName('body')[0].onclick = clickFunc;
hideBusysign();
Wicket.Ajax.registerPreCallHandler(showBusysign);
Wicket.Ajax.registerPostCallHandler(hideBusysign);
Wicket.Ajax.registerFailureHandler(hideBusysign);
}
function hideBusysign() {
document.getElementById('busy').style.display ='none';
}
function showBusysign() {
document.getElementById('busy').style.display ='block';
}
function clickFunc(eventData) {
var clickedElement = (window.event) ? event.srcElement : eventData.target;
if (clickedElement.type.toUpperCase() == 'BUTTON' || clickedElement.type.toUpperCase() == 'SUBMIT') {
showBusysign();
}
}
Basically, it shows a little busy indicator within my website.
I also have an onload function in my body tag, this is new and helps me focus on the username text field when the page loads.
<body lang="de" class="fade-in one" onLoad="document.forms.login.username.focus();">
However, since I added this last functionality, the busy indicator stopped working because it also uses the onload function. What can I do to make it work again?

it's not the most elegant way .. but it will work
<body lang="de" class="fade-in one" onLoad="document.forms.login.username.focus();setupFunc();">

Remove your body onload tag and put:
<script type="text/javascript">
window.onload = function() {
document.forms.login.username.focus();
setupFunc();
};
</script>
After your external Javascript (make sure it's still in the <head> tag). That should change window.onLoad to your custom function, which does what you need and then calls setupFunc.

Related

Show loading while waiting for server

I want to modify a js script to be fired when the client is waiting for the server instead of fireing on loading. There you can see the script: FakeLoader.js, CSS
I found an ajax solution here, but I had no idea how to use it, as the script is inicialized in html. I think the key is at the end of the js file:
$(window).load(function(){
centerLoader();
$(window).resize(function(){
centerLoader();
});
});
On the html page, I have a text input field, which makes refresh on hitting enter, so I thought I could solve it by replacing the mentioned part with code from here :
$(document).keypress(function (e) {
if (e.which == 13) {
centerLoader();
$(window).resize(function(){
centerLoader();
});
}
});
This should fire the loader when enter was hit and show it while the server sends the new page, but instead it just does exatly the same thing before modifying the script, which is weird.
This is how it is initialized in html:
<div id="fakeLoader"></div>
<script type="text/javascript">
$("#fakeLoader").fakeLoader({
timeToHide:1200, //Time in milliseconds for fakeLoader disappear
spinner:"spinner1",//Options: 'spinner1', 'spinner2', 'spinner3','spinner4', 'spinner5', 'spinner6', 'spinner7'
});
</script>
Could you give some idea? I am not good at js. Thank you.
I have a working sample with this:
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="3.2.1" src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="http://joaopereirawd.github.io/fakeLoader.js/js/fakeLoader.js"></script>
<link rel="stylesheet" href="http://joaopereirawd.github.io/fakeLoader.js/demo/css/fakeLoader.css" />
<script>
window.onload = () => {
document.body.addEventListener('keydown', function (e) {
if (e.keyCode == 13) {
$("#fakeLoader").fadeIn();
$("#fakeLoader").fakeLoader({
timeToHide:1200, //Time in milliseconds for fakeLoader disappear
spinner:"spinner1",//Options: 'spinner1', 'spinner2', 'spinner3','spinner4', 'spinner5', 'spinner6', 'spinner7'
});
}
});
}
</script>
</head>
<body>
<h1>Hello Plunker!</h1>
<div id="fakeLoader"></div>
<script type="text/javascript">
$("#fakeLoader").fakeLoader({
timeToHide:1200, //Time in milliseconds for fakeLoader disappear
spinner:"spinner1",//Options: 'spinner1', 'spinner2', 'spinner3','spinner4', 'spinner5', 'spinner6', 'spinner7'
});
</script>
</body>
</html>
Obviously that's not how you will want the end result to look. It'll be better to move the fake loader part to a function and make the keyCode stuff cross browser. That'll get you started though.

HTML onload not working

I'm attempting to use html onload event to trigger javascript, but is not working. The original code was:
html:
<div id='map' onload="generateMap.createMap();"></div>
JS:
var generateMap = function(){
return{
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
}
In an attempt to test, I changed the html to:
<div id='map' onload="alert('test');"></div>
Can anyone tell me why nothing is working?
First, the onload attribute is not valid for a div tag. You most likely intended to place the onload in the body tag.
Unfortunately, that's not the only problem.
In your onLoad you are referencing generateMap as if it is an object with method createMap. However, this is not the case. You have assigned generateMap to an anonymous function.
To get your code working, generateMap needs to be an object with method createMap.
You just need to set it as an object in the first place:
var generateMap = {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
Or if you need to retain the anonymous function for whatever reason, you can use an immediately executing function:
var generateMap = (function(){
return {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
})();
There is no onload event for a div. You can use the script tag just after the div tag to emulate onload behavior.
Use this
<head>
<meta charset="utf-8">
<script type="text/javascript">
var generateMap = {
createMap: function(element) {
navigator.geolocation.getCurrentPosition(initialize);
}
};
</script>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
generateMap.createMap('map');
</script>
</body>
Assuming Chrome.. div tags do not have an onload event. Check the following two jsfiddles:
Does not work:
http://jsfiddle.net/o81e4dkr/
Works:
http://jsfiddle.net/p3osqrdn/
I do not know of a way to have an event fired when a div is loaded, unless it is being loaded in via jQuery.load(), in which case you can use the callbacks.
If you're using jQuery then I like the following function which adds onload capability to all tags:
$(document).ready (function () {
jQuery.each ($("[onload]"), function (index, item) {
$(item).prop ("onload").call (item);
return false;
});
});

Calling Javascript method defined above on page load

I am brand new to JavaScript so bear with me. I have a JavaScript function that is on my page:
<script type="text/javascript">
Sys.debug = true;
var popup;
Sys.require(Sys.components.popup, function () {
popup = Sys.create.popup("#popup", {
parentElementID: "target",
});
});
</script>
It works perfectly when I use it as an event:
<input type="button" onclick="popup.show()" value="Edit Theme" style="float: right; margin-right: 7.25em;" />
I want to call it on page load, inside the body tag I have the following code:
<script>
window.onload = popup.show;
</script>
The method does not appear to get called. What am I doing wrong?
Based on the documentation on Sys.Require, it seems that Sys.Require is called on load, which means that based on the ASP.Net page lifetime the script hasn't loaded when the onload event fires.
It looks like you can use Sys.onReady() instead:
Sys.onReady(function(){
popup.show();
})
You should write:
window.onload = popup.show;

Javascript: Eventhandler not functioning, works in JSFiddle

So this is an answer to another question I posted and I think it is the correct solution. However, while it works wonderfully in jsfiddle it does not function whatsoever outside of that environment. I have tried multiple combinations and I cannot get this thing to work right.
I've tried onLoad in the body, Window.onload both in the header wrapping around the function and separately calling it at the base of the page after all the elements have loaded. Nothing works.
I always get this issue:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Which is frustrating, because all other solutions to this error I have seen revolve around ensuring you do in fact have the specified ID the handler triggers off of in your HTML. Which I do.
I know its probably overkill to make a post here on this but I'm yanking my hair out.
Here's the JSfiddle: http://jsfiddle.net/fFW5r/1/
Here's a mockup page I made to test the concept (which never works):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var link_container = document.getElementById('links');
function myFunction(){ link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
</head>
<body onload="myFunction()">
<div id="links">
Inbound Link
Outbout Link
</div>
<script>window.onload=myFunction()</script>
</body>
</html>
This particular iteration I was trying to test it with the onload call at the bottom of the page after everything had loaded.
var link_container = document.getElementById('links'); need to be executed on document.onload so it has to be inside myFunction
In jsfiddle, the code is executed on load by default. in the fiddle at the left side panel > second select box if you select no wrap - in head you can recreate the problem.
Demo: Fiddle
<script type="text/javascript">
function myFunction(){
var link_container = document.getElementById('links'); // <<-- Move it inside `myFunction()`
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
The reason it doesn't work is that you are initializing link_container before the DOM is ready. Then when myFunction() runs, link_container has been initialized to undefined. Which causes it to fail. Initializing it in the function (after the DOM has loaded) should fix the issue
Put declare link_container inside the function.
var link_container = document.getElementById('links');
function myFunction(){
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}

Best way to modify an element that is not yet created

I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.

Categories