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;
});
});
Related
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="/jquery-2.1.0.min.js"></script>
<title>Title!</title>
<script type="text/javascript">
var x = false;
function foo() {
alert (x);
return true;
}
window.onload = function() {
$('#my_form').attr('onsubmit', foo);
$('a').click(function(e) {
x = true;
$('#my_form').submit();
return false;
});
}
</script>
</head>
<body>
<form id="my_form" action="">
<input type="submit">
</form>
Click here!
</body>
</html>
The 'a' click function sets the variable x to be true, why it is false when foo() is run?
Raw JS events do not work the same way as jQuery events. Don't mix the two.
attr allows you to supply a function as the second parameter. That is why your code fires immediately. It is simply assigning the return value to the attribute, e.g. onsubmit="true"
Your current fiddle fires the foo handler as soon as you run this line:
$('#my_form').attr('onsubmit', foo)
You probably meant something like this (or equivalent), but it does not work either:
$('#my_form').attr('onsubmit', "javascript:foo()");
Here is the jQuery equivalent:
var x = false;
function foo() {
alert (x);
return true;
}
$(function() {
$('#my_form').submit(foo);
$('a').click(function(e) {
x = true;
$('#my_form').submit();
return false;
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Lf8hhwvq/
The shortcut DOM ready handler I use above, $(function(){...});, also acts as an IIFE, so you can move the related code inside it:
$(function () {
var x = false;
function foo() {
alert(x);
return true;
}
$('#my_form').submit(foo);
$('a').click(function (e) {
x = true;
$('#my_form').submit();
return false;
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Lf8hhwvq/1/
There are quite a few problems with this code. First of all, you are mixing old parts of the DOM API with jQuery. In your case I would recommend just to stick to jQuery. Amongst other things:
You should put all render-blocking code (that includes code that changes the DOM) before the </body> Tag, not in the <head>. Depending on the size of your JavaScript dependencies, your page will load very slowly.
Don't use window.load =, especially if jQuery has its very own $(document).ready() function, that probably meets your needs even better.
If you want to set an event handler, don't try to set it with the attr function. That's a very old way of doing it and also the source of your problem. Use the jQuery .on() function instead (the jQuery equivalent of .addEventListener).
If you can avoid it, don't use global variables. Wrap all your code in an IIFE instead.
Thus, your code becomes:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title!</title>
</head>
<body>
<form id="my_form" action="">
<input type="submit">
</form>
Click here!
<script src="/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var x = false;
function foo() {
alert (x);
return true;
}
$('#my_form').on('submit', foo);
$('a').on('click', function(e) {
x = true;
$('#my_form').submit();
return false;
});
});
</script>
</body>
</html>
Codepen: http://codepen.io/anon/pen/zvaOLR
I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id='content'>Content.....</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script src='js/script.js' type='text/javascript'></script>
</body>
</html>
// script.js //
$('#content').click(function(){
$('body').append('<div id="apended">Click me!</div>');
});
$('#apended').click(function(){
alert('click!');
});
When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:
$(document).on('click', "#appended", function (e) {
// some code code
alert('click!');
});
or:
$("body").delegate("#appended", "click", function () {
// your code goes here
alert('click!');
});
For more information read article about Understanding Event Delegation
Instead of click function You can use :
1.live(old version)
2.delegate
3.on
But , if you want to use click with immutation of delegate function :
var myFn=function(e){
if(e.target.id=='apended'){
alert('click');
}
}
$(document).click(myFn)
Demo :http://jsfiddle.net/abdennour/7cyjV/
I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.
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.
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.