Is it possible to have keyboard event listener canvas.addEventListener('onkeydown', ev_keydown, false); like we have Mouse event Listeners
canvas.removeEventListener('mousedown', ev_mousedown, false);
canvas.addEventListener('mousedown', ev_mousedown, false);
in JavaScript.
If not then what would be the alternate?
Check if this works for you. Your sample line had the a prefix of on which is only used for IEs method attachEvent.
function listener(elem, evnt, func)
{
if (elem.addEventListener)
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) // For IE
return elem.attachEvent("on" + evnt, func);
}
listener(document.getElementById('myCanvas'), 'keydown', ev_keydown);
jQuery offers a simple way to bind eventlisteners to DOMElements
and there are also eventlisteners for keyboard events here are some links
http://api.jquery.com/keydown/
http://api.jquery.com/keypress/
http://api.jquery.com/keyup/
you can bind them to window and this should do what you want
you can also use your own method to bind events in a cross-browser compatible way
function bindEvent(e, typ, handler) {
if(e.addEventListener) {
e.addEventListener(typ, handler, false);
}else{
e.attachEvent('on'+typ, handler);
}
}
this should also allow you to bind the mentioned types of events
Related
I am trying to figure out what the code below is trying to do. Usually if I am trying to change the url then document.location= url is enough. I know Event.cancelBubble is used to prevent clicks from propagrating to other views but in this case we're changing the URL and event is not declared anywhere in the javascript so what is it and event.returnValue=false trying to achieve in this case?
function gotoUrl(url) {
document.location= url;
event.returnValue=false;
event.cancelBubble=true;
}
This is the IE 8 (and less) proprietary way to cancel an event (event.returnValue = false) and prevent it from bubbling up to other DOM objects (event.cancelBubble = true). In IE's world event was a Global and since only one event can ever be happening at one time, the current event object would always be found by using the Global event object. You didn't have to declare a callback function argument to access it.
But, what you should understand about cancelling events is that you are not cancelling the execution of the previously set up event handler (you need to de-register the event handler for that). What you are doing when you cancel an event is cancelling the "native" behavior of that event on the element in question. So, with your code, the location will still be changed because gotoUrl() is still being invoked and its code will still run. But, depending on what type of element this event callback is registered to and what kind of event is was handling, that native behavior will be cancelled.
Some simple examples would be
A form element's submit event callback might decide to cancel the
submit event if form validation fails -- the event handler will
still run, but the actual event (submitting the form data) won't.
A hyperlink's click event callback might be cancelled for some
reason. The code in the click event callback will run, but the
native behavior (the navigation) won't. You can see this in my
example below.
For someone interested in writing cross-browser compatible code, the following was very common back in the day. (The Stack Overflow snippet environment doesn't allow navigation, but you can do that test here in this Fiddle):
var btnWire = document.getElementById("wire");
var btnUnwire = document.getElementById("unwire");
var link = document.getElementById("anchor");
function foo(evt){
alert(evt.currentTarget.nodeName + " was " + evt.type + "ed!");
}
function foo2(evt){
// This click event handler for the link actually cancels the event
// so that native behavior (navigation in this case) won't happen
// and the event won't bubble.
cancelEvent(evt, false);
// But the event callback itself (this function) will still run:
alert(evt.type + " cancelled on " + evt.currentTarget.nodeName);
}
// Set up event handler for first button, link and document
wireUp(btnWire, "click", foo , false);
wireUp(link, "click", foo2, false);
// This won't fire for the link at all because that event is cancelled
// And it won't fire for the first button after the 3rd button is clicked
wireUp(document, "click", foo, false);
// Set up event handler on second button that removes first button's event handler
wireUp(btnUnwire, "click", function(){ unWire(document, "click", foo , false); }, false);
// Cross-browser event wiring code
function wireUp(element, eventName, callback, capture){
// Use feature detection to determine what event model is supported
if(window.addEventListener){
console.log("DOM Event Model Supported");
element.addEventListener(eventName, callback, capture);
} else if(window.attachEvent) {
console.log("IE 8 or less Event Model");
element.attachEvent("on" + eventName, callback);
} else {
console.log("Only DOM Level 0 support");
element["on" + eventName] = callback;
}
}
// Cross-browser event removing code
function unWire(element, eventName, callback, capture){
// Use feature detection to determine what event model is supported
if(window.removeEventListener){
// DOM Event Model Supported
element.removeEventListener(eventName, callback, capture);
} else if(window.attachEvent) {
// IE 8 or less Event Model
element.detachEvent("on" + eventName, callback);
} else {
// Only DOM Level 0 support
element["on" + eventName] = null;
}
}
// Cross-browser event cancellation code
function cancelEvent(event, bubble){
// Make sure a proper reference to the event is gotten
event = event || window.event;
// Use feature detection to determine what event model is supported
if(window.addEventListener){
// DOM Event Model Supported
event.preventDefault();
!bubble ? event.stopPropagation() : null;
console.log(event.type + " event and bubbling cancelled with DOM standard.");
} else {
// IE 8 or less Event Model
event.returnValue = false;
!bubble ? event.cancelBubble = true: null;
console.log(event.type + " event and bubbling cancelled with IE Model.");
}
}
<button type="button" id="wire">Click to test Event Callback</button>
<div>
Navigation won't work because click event is cancelled
</div>
<button type="button" id="unwire">Click to Remove Event Handler on document</button>
References:
event.returnValue
event.cancelBubble
window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL
window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.
function myFunction() {
alert("The anchor part has changed!");
}
Why I am not able to attach event listener using the addEventListener method ? But window.onhashchange working fine
EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.
There is no onhashchange event. There is a hashchange event:
window.addEventListener('hashchange', myFunction, false);
Likewise, there is no onclick event, but there is a click event:
element.addEventListener('click', someFunction, false);
testing on* properties for bound events is not an appropriate way to verify that a callback is bound. For testing, you'll have to trigger the event in some manner and have a test within the callback:
window.onhashchange = function () {
console.log('onhashchange property works');
};
window.addEventListener('hashchange', function () {
console.log('addEventListener method works');
}, false);
Click this to test
Successfully bound callbacks will not be exposed via the property.
I am checking for any interaction using JQuery's .one() function.
var myEvents = 'mousedown mousemove mouseup touchstart touchmove touchend mouseout';
jQuery(document).one(myEvents, function(){
//do something only once.
});
But I would like all these to be ubinded once any of these events has fired. I know I can unbind again with jQuery(document).unbind(myEvents), but was wondering if there was a clean inbuilt way of simply unbinding after one event.
EDIT: Here is a fiddle: http://jsfiddle.net/4HkQy/6/
You could extend jQuery with a function which serves exactly that purpose.
jQuery.fn.extend({
oneForAll: function(events, handler) {
var that = this,
oneForAll = function() {
that.unbind(events, oneForAll);
handler.apply(this, arguments);
};
that.on(events, oneForAll);
}
});
You would use it exactly the way you used one it would just be oneForAll.
JSFiddle: Demo
use .off()
jQuery(document).one('mousedown mousemove mouseup touchstart touchmove touchend mouseout', function (event) {
console.log(event.originalEvent.type);
jQuery('p').append(event.originalEvent.type);
//remove all handlers
jQuery(document).off('mousedown mousemove mouseup touchstart touchmove touchend mouseout');
});
But i would recommend using a namespaced handlers so that you won't remove any other event handlers by mistake.
jQuery(document).one('mousedown.myonce mousemove.myonce mouseup.myonce touchstart.myonce touchmove.myonce touchend.myonce mouseout.myonce', function (event) {
console.log(event.originalEvent.type);
jQuery('p').append(event.originalEvent.type);
//remove all handlers
jQuery(document).off('.myonce');
});
Demo: Fiddle
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", handler, false);
document.addEventListener("readystatechange", handler, false);
window.addEventListener("load", handler, false);
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", handler);
window.attachEvent("onload", handler);
}
Above codes is taken from a site.
Questions:
why for DOMContentLoaded and readystatechange, we use document.addEventListener(); while load, we use window.addEventListener(), why?
For readystatechange, we can use in IE this way:document.attachEvent("onreadystatechange", handler);, how aobut DOMContentLoaded? is there a way that we can use it in IE?
Context, who owns the events you are trying to listen. You don't listen for events on <button> elements when you want to listen to <input> elements :D
DOMContentLoaded is supported natively in IE9+. Prior to IE9, readystatechange can be used.
I want to add either a scroll event listener or a touchstart event listener. Initially I used the touch event to deactivate the scroll event listener as shown in the code below:
window.addEventListener('scroll', scrollStart, false);
window.addEventListener('touchstart', touchStart, false);
function scrollMenu() {
// do something
}
function touchStart(e) {
window.removeEventListener('scroll', scrollStart);
// do something
}
But I realized that on some occasions, the scroll event is triggered as soon as the page loads. Therefore, I cannot use the aforementioned method. Is there another way to check if the browser supports a touch event listener without adding the event?
Does Modernizr solve your problem? See example here for the various ways to detect touch events and each one's browser compatibility:
http://modernizr.github.com/Modernizr/touch.html
You should be able to check whether the ontouchstart attribute exists in the window:
if ("ontouchstart" in window) {
window.addEventListener('touchstart', touchStart, false);
} else {
window.addEventListener('scroll', scrollStart, false);
}
... I can't confirm the x-browser-ness of this though.