JavaScript event handlers -why no alert? - javascript

I'm a newbie at JavaScript trying to learn event handlers. Looking at this fiddle http://jsfiddle.net/mjmitche/uV4kv/ can anyone tell me why the pop up is not appearing when the link is clicked?
I've also copied the code below
click me
function addEventHandler(oNode, sEvt, fFunc, bCaptures){
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+sEvt, fFunc);
else
oNode.addEventListener(sEvt,fFunc,bCaptures);
}
function onLinkClicked(e) {
alert("you clicked the link");
}
function setUpClickHandler(){
addEventHanlder(document.getElementById('clickLink'), "click", onLinkClicked, false);
}
addEventHandler(window,"load",setUpClickHandler,false);

There are basically three problems:
You have some typos, e.g. "Hanlder" instead of "Handler" and "Sevt" instead of "sEvt".
The code is already run after page load, so the event handler you add to window will never be called. Change in jsFiddle from onLoad to no wrap (head).
You "IE detection" does not work. I get this error in Chrome:
Uncaught TypeError: Object http://fiddle.jshell.net/_display/# has no method 'attachEvent'.
Better would be to test whether the function window.attachEvent exists. I also think that window.event is only available when an event is raised.
If this is corrected, your code will run (DEMO).
Further notes:
Testing which method is supported (i.e. attachEvent or addEventListener) on every call of your function is unnecessary. It won't change during the life of the page. Better is to test only once at the beginning. Example:
var addEventHandler = (function() {
if(window.attachEvent) {
return function(oNode, sEvt, fFunc) {
oNode.attachEvent("on"+sEvt, fFunc);
};
}
else {
return function(oNode, sEvt, fFunc, bCaptures) {
oNode.addEventListener(sEvt,fFunc,bCaptures);
};
}
}());
This assigns a function the supported function to addEventHandler.

A couple of problems:
You have a recurring typo, "Hanlder" instead of "Handler". There are at least two, one where you do your setUpClickHanlder (sic) function, and one within it (addEventHanlder).
Also, you have "Sevt" where you mean "sEvt". (JavaScript is case sensitive.)
Let tools help you. Use a browser that gives you a console showing errors. Use a debugger for single-stepping through code, looking at variable values at runtime with inspectors, etc.

Your addEventHandler needs adustment:
function addEventHandler(oNode, sEvt, fFunc, bCaptures) {
oNode.attachEvent ? oNode.attachEvent ("on" + sEvt, fFunc) :
oNode.addEventListener (sEvt, fFunc, bCaptures);
}
It is in event handlers themselves that you need to check for window.event

Related

onreadystatechange event function [duplicate]

I am using the following code and it works perfectly fine in Chrome.
function dayBind(xyzValue) {
if(event.type == 'click')
alert('Mouse Clicked')
}
Note that there was no 'event' variable passed to the function but still it was available for me in case of chrome. But when I use Firefox I get 'event' undefined.
I tried using the following workarounds:
var e=arguments[0] || event;
also:
var e=window.event || event;
But none of them worked for me. Is there any 'event' equivalent in Firefox?
Because IE and Chrome put the event in the global object window, so you can get it. In firefox, you need to let the first parameter be the event.
function dayBind(event, xyzValue) {
var e=event || window.event;
if(event.type == 'click')
alert('Mouse Clicked')
}
If you're setting up the handler with an "onclick" attribute or something (which, since you tagged the question "jQuery", you really should consider not doing), you have to explicitly pass it:
<button type=button onclick='whatever(event)'>Click Me</button>
If you need it to work cross browser, simply use the arguments object:
function dayBind()
{
var e=arguments[0];
if(!!e && e.type === 'click')
{
alert('Mouse Clicked')
}
}
References
Overview of Events and Handlers
DOM Event Handlers
eventTarget.addEventListener
I am working in a plugin's callback function. I cannot call it myself.
One simple question to your suggestion: when you write: onclick="whatever(event)" you are writing javascript in the value of onclick attribute, right?
Why can't you make the same function call inside some other function like this:
function foo(){ whatever(event); // this is also javascript }
// But this doesn't work for me in FireFox 10.0.2
The code in the "onclick" attribute should be thought of as part of a function that the browser creates for you. That function automatically has the "event" parameter available. Writing the attribute as I did in the answer cause that parameter to be passed on the your other function.
Really, you should read about the jQuery API and use that to bind event handlers instead of using "onclick" and other similar attributes.

How to tell if a popup will get blocked

I appreciate how browsers work when deciding whether a window.open() was triggered by a click, as in, its only allowed when it came from a real element click event.
I want to write the same logic myself, how do I do that?
Say I have any JS function, called potentially anywhere and everywhere from the rest of my application, sometimes with a click event handler at the start of the callstack and some times not. How can I know this inside my method, without explicitly passing information about the start of the stack (click vs not) all the way around my application?
function iNeedToKnowIfStackFrame0WasAClickEventListener() {
var wasAClick = ???;
if(wasAClick)
window.open(...);
else
something.else();
}
You can get the event information using this.event.type.
You can either pass the event into the function like so:
function iNeedToKnowIfStackFrame0WasAClickEventListener(event) {
var wasAClick = event.type == "click";
if(wasAClick)
window.open(...);
else
something.else();
}
or you can get the event off this
function iNeedToKnowIfStackFrame0WasAClickEventListener() {
var wasAClick = this.event.type == "click";
if(wasAClick)
window.open(...);
else
something.else();
}

Event Object Storage

I am new to scripting and for a function(e) e is event object can anyone please update me for my few concerns
it will created when a event is triggered so when it will removed . so every event an object is created?
where these objects get stored?
That is just an event handler variable.
Doesn't matter if its e or event
It really doesn't matter whether you use e or event or anyother word for this.
function (e):
When you use this:
function (e) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/1/ (fiddle for function (e))
function (event):
This is just a name you're giving to the current event, you can change that to
function (event) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/2/ (fiddle for function (event))
function (something):
Or even to this:
function (something) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/3/ (fiddle for function (something))
Their usage
You use these, to get the methods for the current object; such as event.keyCode, to get the keyCode which is used in a function where keyboard is used.
Where they are present
They are included in JavaScript and you don't need any more dependendies for it to work and you don't need any more coding work for it.
What a function looks like
They aren't removed, once a function is executed, it has an event parameter or what you can call argument. as:
function (event) { // event is the argument
if(event.keyCode == 13) { // using its method of keycode
/* and comparing its value to 13
* 13 is for enter
* you get a bool value; either true of false and do the coding */
}
}
Simple answer
From the fiddles you will get to the result that e doesnot require to be e only. It can be anything that you want to be written in the code. Something is no method in JavaScript, but usage of it at the first argument made it an event handler, and it got the methods of event.
They are not stored in browser, they are a part of every browser! When you say a browser supports this feature it means it includes all the files that are required to run a code.

inline javascript onclick event

This is my html code
Hit
This is my javascript file
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
But when i click the Hit Link, it redirects.
you need to pass in the event if you wish to preventDefault.
html:
Hit
script:
function runFunction (evt) {
evt.preventDefault();
evt.stopPropagation();
}
To tie both of the very-correct answers together, what's happened is you've inlined a function where you've written onclick="return runFunction();"
If you look at that, what it's really doing is going like this:
var link = document.getElementById("myLink");
link.onclick = function () { runFunction(); };
See the problem?
My runFunction is being called without any event object passed in, at all.
...which means that var thisLink = (evt) ? is going to return false, which means that it's going to try to run in oldIE-mode.
By writing onclick="runFunction", that's the same as saying:
link.onclick = runFunction;
Which means that when the onclick event happens, runFunction will be called, and in W3C-compliant browsers, it will be sent an event object.
Which is why that solution works.
The best way to avoid a lot of this confusion is to deal with JavaScript from inside of JavaScript, and to deal with HTML inside of HTML, so that you don't have to worry about how strings translate into code.
Now, to get all of this to work, AND prevent redirection, you want to do this:
for W3C browsers (the ones that pass the event parameter):
function runFunction (evt) {
// stops the default-action from happening
// means you need to find another way to fire it, if you want to later
evt.preventDefault();
// stops higher-up elements from hearing about the event
// like if you stop a submit button from "clicking", that doesn't stop the form
// from submitting
evt.stopPropagation();
//the oldIE versions of both of these are
event.cancelBubble = true;
event.returnValue = false;
}
When I plugged your code into chrome, I got this as the error in the console:
Uncaught TypeError: Cannot read property 'srcElement' of undefined
IF the javascript bombs out while processing, it never gets a chance to return at all so the browser tends to disregard what is in the onclick handler after the exception.
Since it bombed out... default behavior of anchor tags, which is to send you off to wherever the href says to go.
Try wrapping the contents of the function in a try/catch block and see what turns up if this kind of thing plagues you.

Run function only if event default is/isn't prevented

Is there a way to run a function only if event.preventDefault() is called on an event (by another unknown function). This is for a jQuery plugin, so I don't have any knowledge of what other parts of the page might be doing. I've tried this:
Event.test = Event.preventDefault;
Event.preventDefault = function () {
alert('Success');
this.test();
}
but it doesn't work... just behaves as normal, with no errors.
Conversely, I want the opposite too... to call a function only if event.preventDefault() isn't called. In effect, to add a function to the default action for an event. Any ideas? Is all this at all possible?
Edit: Based on the comment, I've got a solution to the first problem: http://jsfiddle.net/nathan/VAePB/9/. It works in Chrome (alerts function preventDefault() { [native code] }, but IE alerts undefined. So IE won't let me define Event.prototype.test, but it will let me redefine Event.prototype.preventDefault. Weird. I'm sure I can come up with a solution to the the second problem based on this one if I can just get it to work in IE.
I'm not sure I've understand. Can't you just use event.isDefaultPrevented() like this
For the first problem, try something like this:
oldPreventDefault = Event.prototype.preventDefault;
Event.prototype.preventDefault = function() {
//do stuff
oldPreventDefault.call(this);
}
I don't know if that will work, but it might be worth a shot.
For the second problem, I would try something similar to live event handling. Put a listener on a parent element (i.e. body or a top-level div). If you can get your hook into preventDefault as noted before, you can use that to set a flag. If the event bubbles up to that element and your flag isn't set, do your extended behavior. Though this won't work with all events, since not all events bubble. Another way to tackle this problem might be to delay execution until the current stack has finished using setTimeout(0,...) and then checking the flag.

Categories

Resources