Calling onload event with more than function call - javascript

I have something like this in my html:
<body onload='myjavascriptfunction1()'
I also want to be able, with the same onload event to call 'myjavascriptfunction2() along with myjavascriptfunction1()'. Please, is this possible?

You can do it like this:
<body onload='myjavascriptfunction1();myjavascriptfunction2()'>
or create a function and then call from that function the other functions you want
function myjavascriptfunction1(){
myjavascriptfunction2();
myjavascriptfunction3();
}

Use a generic OnLoad function
<body onload='onLoad()'>
function onLoad(){
myJSFunction1();
myJSFunction2();
}
But a better way would be to subscribe to the onload event using addEventListener
window.addEventListener("load", myJSFunction1, false);
window.addEventListener("load", myJSFunction2, false);
JSFiddle
This keeps your JS separate from your HTML and prevents you from adding the ugly onLoad attribute to the body tag.

Attach Event Listeners rather than defining onload events in the markup
document.body.addEventListener("load", do_something(), false);
function do_something() {
alert("hello universe");
//do something here
}
Refer to Event Listeners documentation for more info. If your event listener has to work on multiple browsers like legacy IE's you might have to define other event listeners like attachEvent. Libraries like jQuery are handy for these needs as you don't have to worry about browser compatibilities.

Related

What is meant by "onload=foo(event)"?

I am new to JS and found this code section:
<body>
<span id="sp1">
<img src="aurora.gif" onload="ev1(event)">
</span>
</body>
As far I understood, the onload attribute gets triggered if the entire HTML Doc finished "loading". But I don't really understand, whats passed to the ev1 function if the onload attribute is triggered. What is event in this case?
Here is the source code
It's hooking up a handler to the image's load event and passing the event object for the event into the handler. The event object exists reliably cross-browser within the context of the onload attribute-style event handler: On IE, it's a global; on Firefox, it's a local within a synthetic function created for the onload handler; on Chrome, I think it's both. :-)
Note that the ev1 function must be a global, which is one of many reasons not to use onxyz-attribute-style event handlers.
img also has onload attribute & is called when when the image has finished loading. Similarly it also have onerror event handler. event represent the event object.
function ev1(e) {
console.log(e)
console.log('Img loaded')
}
img {
width: 200px;
height: 200px;
}
<img src='https://i.redd.it/xbq78cnv2nr21.jpg' onload='ev1(event)'>
This appears to be an attempt pass the Event Object as an argument to a function called ev1.
Instead of using an inline event, the author developer should have used a JavaScript event, like this.
document.querySelector("img").addEventListener("load", event => {
console.log(event);
});
Good luck.

Call onclick="function(this);" on load?

I have a checkbox with the following code:
<input type="checkbox" id="check" onclick="function(this);" checked="checked" />
But in same cases I want the call to be made on page load.
How do I replicate the "this" manually?
I tried adding onload="function(this);" to the input, but that didn't work.
And if I just call "function();" on page load then the function naturally doesn't work.
So it'd be great if I could manually call a function like: function(htmlElement[check]); or whatever "this" constitutes.
Hope I've made myself clear :)
In your case, this will refer to the input element. Since that element has an ID, you can easily get a reference to it with the getElementById method):
yourFunction(document.getElementById("check"));
You can place that in the onload attribute of the body element, but ideally, stop using inline event handlers and use the addEventListener method instead.
Try with:
onload="function(document.getElementById('check'));"
You could get the element via id, and do it in the window.onload callback function.
window.onload = function () {
yourFunction(document.getElementById('check'));
}
to the extent of my understanding, onload only works on <body> tag
What you might want to try, is this:
$(document).ready(function() {
// Handler for .ready() called.
});
source:http://api.jquery.com/ready/
You can use something like this:
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
yourFunction(document.getElementById("check"));
}, false );
You must avoid using:
window.onload = function() {
}
because in this way you will overide attached to onload functions (if there is already attached to onload with this way). This method is very good when you want to have JavaScript in separate file (the best solution).

how to not use inline js events?

I am used to using inline events in my websites for example
<head>
<script>
function func() {
alert("test");
}
</script>
</head>
<body>
<div id="mydiv" onclick="func()"></div>
</body>
I noticed that sites these days do not use inline events at all. I know you can set events pragmatically like:
document.getElementById('mydiv').onclick = function(){ func()}
Is this how it should be done? Do I have to put the above line at the end of every page?
How are the keypress,click, and blur events attached to the input fields on this site for example: https://twitter.com/signup
Thanks.
Yes, that is one valid way to add an event to an object, but it prevents more than one function from being bound at a time.
I would recommend looking into jQuery (or similar javascript library, like mootools), which is how the vast majority of sites bind their javascript events these days.
For example, in jQuery you generally bind clicks like this:
$("#mydiv").click(function(event) {
// click handling code
});
The cleanest way to add event listeners is to use the built in methods :
var el = document.getElementById('mydiv');
if (el.addEventListener) {
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', modifyText);
}
function modifyText() {
}
This promotes cleaner more readable and reusable code. (Note attachEvent is for pre IE9)
You can either place this code at the end of the <body> tag (or anywhere within the <body> tag but after the DOM element is added) or within a window onload function - which executes after the DOM has completed loading :
window.onload = function() {
// here
};
The prefered method is to use addEventListener, often in combination with a library (such as YUI or jQuery) that smooths over variations between browsers (e.g. old-IE not supporting addEventListener).
Do I have to put the above line at the end of every page?
Usually you would put JavaScript in a file of its own, and then src it into each page that needed it.
The main idea here is that the DOM element that you want to register the handler on should be loaded. so either you do the event binding after the element html, or you could do it in the window.onload event handler, which could be defined before the actual tag definition, like this:
window.onload = function(){
// your event binding
}
But my advice would be to include javascript at the end of the document as much as possible.

Separate Event Handler for Reusability

I have a simple click handler that will alert its link's href as in:
<a id="link" href="http://www.google.com">Google</a>
$('a#link').on('click', function() {
alert($(this).attr('href'));
});
How can I separate the function (and how to call it) so that it can be called by another click handler?
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
// I'd like a#another-link to be able to call that same function above.
<a id="another-link" href="http://www.microsoft.com">Microsoft</a>
$('a#another-link').on('click', /* How to call showHref? */);
Thanks.
You could do something like this:
function showHref() {
alert($(this).attr('href'));
}
$('a#link').on('click', showHref);
$('a#another-link').on('click', showHref);
In this code, this inside the showHref will refer to the link being clicked, since jQuery makes sure that the link being clicked is the calling context (using .call() which you may want to read up on). If, however, you were to manually call showHref, this would not refer to your link.
If you want a definition of showHref that you could both call manually, and bind through jQuery, it would probably be neatest to pass the reference as a parameter:
function showHref(link) {
alert($(link).attr('href'));
}
In that case, you'd have to adjust your listeners as follows:
$('a#link').on('click', function() {
showHref(this);
});
But it is also possible to combine selectors:
$('a#link, a#another-link').on('click', function() {
alert($(this).attr('href'));
});
You can put the function logic into a reference like this:
var handler = function () {
alert($(this).attr('href'));
};
Then you can use that reference to initialize event listeners:
$('#link').on('click', handler);
Of course, you can reuse that.
$('#some_other_link').on('click', handler);
Or call that yourself outside of an event handler context (which normally wouldn't make sense if you're fashioning an event handler function --- but it can be done with lambdas in general).
handler();
But if you want to just trigger the event on an element, you should call the corresponding event trigger function.
$('#link').click();
// or
$('#link').trigger('click');
You wrote:
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
Umm, actually, yes it will. That's exactly the promise made by DOM events and also event handlers registered with jQuery.
FWIW, the content should just be:
alert(this.href)
There's really no need to invoke jQuery just to get the element's href attribute.

Cancel jQuery event handling

I have setup onclick event handler in the following manner:
element.onclick = function() { /*code */ }
Imagine there are event handlers setup using jQuery method bind() or similar handlers.
$('element').bind('click', function(){/*another function*/})
How can I prevent invoking handler defined with jQuery from the handler I have described in the beginning?
NB stopPropagation() and etc. jQuery's methods doesn't work from that function, because it is passed with native event object.
I'm not 100% sure what you're asking but maybe this will help:
You can create a new event object (compliant with W3C DOM) via jQuery's exposed Event constructor:
For example:
element.onclick = function(e) {
var aBetterEventObject = jQuery.Event(e);
// Now you can do what you want: (Cross-browser)
aBetterEventObject.preventDefault()
aBetterEventObject.isDefaultPrevented()
aBetterEventObject.stopPropagation()
aBetterEventObject.isPropagationStopped()
aBetterEventObject.stopImmediatePropagation()
aBetterEventObject.isImmediatePropagationStopped()
}
EDIT: Reading through your question again, I don't think propagation is the problem - you seem to want to cancel an event handler from running within an event handler - I'm not sure this is possible. You could just unbind all handlers (jQuery(elem).unbind('click')) but I don't think that's what you're after...
try to add the following line in the jQuery event handler:
return false;
Following on from JimmyP's answer. I've tried this
$('#x').click( function(e){
alert('hello');
});
document.getElementById('x').onclick = function(){
$('#x').unbind('click');
alert("goodbye");
}
The jQuery event runs once in this example. I don't think you can rely on the order of handlers being invoked however you define them, so I guess you'll have to accept that the jQuery event might fire once. Adding the onclick first does prevent the jQuery event from firing at all but, as I said, I don't think that's reliable.
Jquery has a method for namespacing events. http://docs.jquery.com/Namespaced_Events
You can add, trigger and remove separate functions bound to the same event via namespaces:
$("a").bind("click.custom1",function(){ ... });
$("a").bind("click.custom2",function(){ ... });
$("a").trigger("click.custom2");
$("a").unbind("click.custom2");
As long as you unbind the namespaced event your normal onclick should be unaffected. You may have to bind two separate namespaces to the click event as above if that doesn't work.

Categories

Resources