How do I disable ondblclick in IE8? - javascript

So, I've already tried the selected answer on this:
How to disable ondblclick in JavaScript?
but it doesn't work, on my end. As per usual, I'm suspecting it has something to do with IE8 (since a lot of my previous problems were related to IE8 issues).
This is how my button looks like, keyBtnEvent is a function that changes the class of the div:
function keyBtnEvent(key, id, event) {
//change class of object with id = 'id'
console.log(event + 'event of keyBtnEvent called');
}
<div id="2Key" class="key"
onmouseup="keyBtnEvent('2','2Key','up')"
onmousedown="keyBtnEvent('2','2Key','down')">
<button>2</button>
</div>
So, how do i disable ondblclick in IE8, without using jquery?

This is the proper IE 8 way to do it:
var key = document.getElementById('2Key')
// Feature detection for DOM Event Standard and IE 8 and less
if(window.addEventListener){
// W3C DOM Event Standard
key.addEventListener("dblclick", function(evt) {
evt.preventDefault(); // stop the event
evt.stopPropagation(); // don't bubble the event
});
} else if(window.attachEvent){
// IE 8 or less
key.attachEvent("ondblclick", function(evt) {
evt = evt || window.event;
evt.returnValue = false; // stop the event
evt.cancelBubble = true; // don't bubble the event
});
}
Also, you should not be using inline HTML event attributes (onmouseover, onmouseout, etc.). Here's why. Instead, you should be doing all your JavaScript work in a dedicated script and use .addEventListener() (or the above attachEvent() method for IE 8 or less).

Related

Input with clear icon - loss of focus issue

I have a clearable input like this:
+-----------------+
| x |
+-----------------+
The clear icon is a span with a font glyph in the :before:
<wrapper>
<input>
<icon span>
</wrapper>
Validation of inputs is done on blur (which re-renders the input View for validation message and icon changes - this keeps the architecture simple). The issue I am experiencing is that by clicking the icon the input triggers a blur and then the icon click.
Can you think of a way to either:
a) Avoid triggering a blur -- I can only think of ditching font glyph and using a background image, but I am already using other glyphs for required, invalid etc in that position so it is undesired
b) Detecting that the blur was caused by the icon and not something else
Thanks.
Edit: Here is one idea, a bit lame using a setTimeout though: http://jsfiddle.net/ferahl/td5VR/
Consider using mousedown and mouseup events to set/remove a flag.
http://jsfiddle.net/td5VR/4/
var wasClicked = false;
$('input').blur(function(){
$(".results").text(wasClicked ? "was clicked": "wasn't clicked");
});
$('.something').mousedown(function(){
wasClicked = true;
}).mouseup(function() {
wasClicked = false;
});
Though you still need to disable keyboard navigation to the link by setting tabindex="-1".
Here's a few ideas of what might be happening and some approaches to try:
This is a guess, but perhaps what you're experiencing is something called event bubbling. Take a look at this page to learn more about it. You can prevent event bubbling in your click handler like this:
IconElement.onclick = function(event) {
event = event || window.event // cross-browser event
if (event.stopPropagation) {
// W3C standard variant
event.stopPropagation()
} else {
// IE variant
event.cancelBubble = true
}
}
(If you're using jQuery, you don't need to worry about the "IE variant")
You could also try adding return false; or event.preventDefault() and see if that works.
And one more approach is to check event.target in your blur handler:
InputElement.onblur = function(event) {
event = event || window.event // cross-browser event
var IconElement = [do something to get the element];
if (event.target == IconElement) {
// Ignore this blur event, or maybe even call "this.focus()"
}
}
Here is the final very simple solution inspired by #Yury's answer:
$('.clearable-icon').mousedown(function() {
// This happens before blur, so return false and stop propagation.
return false;
});

Cross-browser: detect blur event on window

I just read, I think all the thread that deals with this subject, and I can't find a real solution to my problem.
I need to detect when the browser window loses its focus, i.e. a blur event.
I've tried all the scripts on stackoverflow, but there doesn't seem to be a proper cross-browser approach.
Firefox is the problematic browser here.
A common approach using jQuery is:
window.onblur = function() {
console.log('blur');
}
//Or the jQuery equivalent:
jQuery(window).blur(function(){
console.log('blur');
});
This works in Chrome, IE and Opera, but Firefox doesn't detect the event.
Is there a proper cross-browser way to detect a window blur event?
Or, asked differently, is there a way to detect a window blur event with the Firefox browser?
Related questions and research:
See Firefox 3 window focus and blur
According to the following github articles, jQuery has discontinued support for Firefox blur testing:
https://github.com/jquery/jquery/pull/1423
http://bugs.jquery.com/ticket/13363
I tried both:
document.addEventListener('blur', function(){console.log('blur')});
and
window.addEventListener('blur', function(){console.log('blur')});
and they both worked in my version of FF (33.1).
Here's the jsfiddle: http://jsfiddle.net/hzdd06eh/
Click inside the "run" window and then click outside it to trigger the effect.
The document.hasFocus (MDN) is an implementation that can resolve the problem with Firefox, but in Opera it isn't supported. So, a combined approach can reach out the problem you are facing.
The function below exemplifies how can you use this method:
function getDocumentFocus() {
return document.hasFocus();
}
Since your question isn't clear enough about the application (timed, pub/sub system, event driven, etc), you can use the function above in several ways.
For example, a timed verification can be like the one implemented on this fiddle (JSFiddle).
It appears that jQuery no longer supports these tests for FireFox:
jQuery bug ticket is here: http://bugs.jquery.com/ticket/13363
jQuery close/deprecation commit is here: https://github.com/jquery/jquery/pull/1423
I am searching for a better way to support Firefox blur eventing, but until I find a better approach, this is a more current status relative to the original accepted answer.
You can use jQuery's blur method on window, like so:
$(document).ready(function() {
$(window).blur(function() {
// Put your blur logic here
alert("blur!");
});
});
This works in Firefox, IE, Chrome and Opera.
I tried using the addEventListener DOM function
window.addEventListener('blur', function(){console.log('blur')});
window.addEventListener('click', function(event){console.log(event.clientX)});
I got it to work after the first blur. but it didnt work when I didnt have the click function attached to it.
There might be some kind of refresh that happens when a click function is interpreted
Here is an alternative solution to your question but it uses the Page Visibility API and Solution is Cross Browser compatible.
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
function onchange(evt) {
var v = "visible",
h = "hidden",
evtMap = {
focus: v,
focusin: v,
pageshow: v,
blur: h,
focusout: h,
pagehide: h
};
evt = evt || window.event;
if (evt.type in evtMap) {
console.log(evtMap[evt.type]);
} else {
console.log(this[hidden] ? "hidden" : "visible");
}
}
// set the initial state (but only if browser supports the Page Visibility API)
if (document[hidden] !== undefined)
onchange({
type: document[hidden] ? "blur" : "focus"
});
})();

Javascript to run a function when input focus

What is the code to run a function, say called "myfunction" when a user clicks within an input box (focus).
I have seen examples in jquery but I cant see how to do it with straight javascript.
use the onfocus attribute
<input type="text" onfocus="someFunc()">
<script>
function someFunc(){
}
</script>
var addEvent = (function(){
/// addEventListener works for all modern browsers
if ( window.addEventListener ) {
/// I'm returning a closure after the choice on which method to use
/// has been made, so as not to waste time doing it for each event added.
return function(elm, eventName, listener, useCapture){
return elm.addEventListener(eventName,listener,useCapture||false);
};
}
/// attachEvent works for Internet Explorer
else if ( window.attachEvent ) {
return function(elm, eventName, listener){
/// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
/// rather than just click, focus, keydown as the other browsers do.
return elm.attachEvent('on'+eventName,listener);
};
}
})();
Using the above cross browser function you can then do the following (once the dom is fully loaded):
addEvent(document.getElementById('your_input'),'focus',function(e){
var input = e.target || e.srcElement;
alert('this input has gained focus!');
});
document.getElementById("elementId").addEventListener("focus",function(e){
//Do Something here
});

Javascript: Capture mouse wheel event and do not scroll the page?

I'm trying to prevent a mousewheel event captured by an element of the page to cause scrolling.
I expected false as last parameter to have the expected result, but using the mouse wheel over this "canvas" element still causes scrolling:
this.canvas.addEventListener('mousewheel', function(event) {
mouseController.wheel(event);
}, false);
Outside of this "canvas" element, the scroll needs to happen. Inside, it must only trigger the .wheel() method.
What am I doing wrong?
You can do so by returning false at the end of your handler (OG).
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
return false;
}, false);
Or using event.preventDefault()
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Updated to use the wheel event as mousewheel deprecated for modern browser as pointed out in comments.
The question was about preventing scrolling not providing the right event so please check your browser support requirements to select the right event for your needs.
Updated a second time with a more modern approach option.
Have you tried event.preventDefault() to prevent the event's default behaviour?
this.canvas.addEventListener('mousewheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Keep in mind that nowadays mouswheel is deprecated in favor of wheel, so you should use
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Just adding, I know that canvas is only HTML5 so this is not needed, but just in case someone wants crossbrowser/oldbrowser compatibility, use this:
/* To attach the event: */
addEvent(el, ev, func) {
if (el.addEventListener) {
el.addEventListener(ev, func, false);
} else if (el.attachEvent) {
el.attachEvent("on" + ev, func);
} else {
el["on"+ev] = func; // Note that this line does not stack events. You must write you own stacker if you don't want overwrite the last event added of the same type. Btw, if you are going to have only one function for each event this is perfectly fine.
}
}
/* To prevent the event: */
addEvent(this.canvas, "mousewheel", function(event) {
if (!event) event = window.event;
event.returnValue = false;
if (event.preventDefault)event.preventDefault();
return false;
});
This kind of cancellation seems to be ignored in newer Chrome >18 Browsers (and perhaps other WebKit based Browsers). To exclusively capture the event you must directly change the onmousewheel method of the element.
this.canvas.onmousewheel = function(ev){
//perform your own Event dispatching here
return false;
};
Finally, after trying everything else, this worked:
canvas.addEventListener('wheel', (event) => {
// event.preventDefault(); Not Working
// event.stopPropagation(); Not Working
event.stopImmediatePropagation(); // WORKED!!
console.log('Was default prevented? : ',event.defaultPrevented); // Says true
}, false)
To prevent the wheel event, this worked for me in chrome -
this.canvas.addEventListener('wheel', function(event) {
event.stopPropagation()
}, true);

oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT

What's the cleanest solution we use to overcome the problem that IE9 doesn't fire the input event when we hit BACKSPACE / DEL / do CUT?
By cleanest I mean code stinks not.
I developed an IE9 polyfill for the backspace/delete/cut.
(function (d) {
if (navigator.userAgent.indexOf('MSIE 9') === -1) return;
d.addEventListener('selectionchange', function() {
var el = d.activeElement;
if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && el.type === 'text')) {
var ev = d.createEvent('CustomEvent');
ev.initCustomEvent('input', true, true, {});
el.dispatchEvent(ev);
}
});
})(document);
For some reason, in IE9, when you delete inside a textfield, the selectionchange event is triggered.
So, the only thing you need to do is: check if the active element of the selection is an input, and then I tell the element to dispatch the input event, as it should do.
Put the code anywhere in your page, and all the deletion actions will now trigger the input event!
I had the same problem. The oninput event fires for backspace, del, etc in Chrome and FF but not IE9.
However, that OnKeyUp does actually fire backspace, del etc in IE9 but not Chrome FF, so the opposite.
I added a specific IE javascript file named ieOverrides.js:
<!--[if IE 9]>
<script type="text/javascript" src="js/ui/ieOverrides.js"></script>
<![endif]-->
Then in the js file I switched the event handlers:
$(document).ready(function(){
$("#search").off('input');
$("#search").on('keyup', function(){
search(this.value);
});
});
Hope that helps.
IE9 doesn't fire the oninput event when characters are deleted from a text field using the backspace key, the delete key, the cut command or the delete command from the context menu. You can workaround the backspace/delete key problem by tracking onkeyup. You can also workaround the cut command problem by tracking oncut. But the only way I've found to workaround the context delete command is to use the onselectionchange event. Fortunately if you use onselectionchange you won't have to track oncut or onkeyup.
Here's some example code based on this technique I've written about:
<input id="myInput" type="text">
<script>
// Get the input and remember its last value:
var myInput = document.getElementById("myInput"),
lastValue = myInput.value;
// An oninput function to call:
var onInput = function() {
if (lastValue !== myInput.value) { // selectionchange fires more often than needed
lastValue = myInput.value;
console.log("New value: " + lastValue);
}
};
// Called by focus/blur events:
var onFocusChange = function(event) {
if (event.type === "focus") {
document.addEventListener("selectionchange", onInput, false);
} else {
document.removeEventListener("selectionchange", onInput, false);
}
};
// Add events to listen for input in IE9:
myInput.addEventListener("input", onInput, false);
myInput.addEventListener("focus", onFocusChange, false);
myInput.addEventListener("blur", onFocusChange, false);
</script>
you could try html5Forms (formerly html5widgets)
Since I hate COBOL, I decided to
update my html5Widgets library to:
Add support for oninput for browsers that don’t support it (e.g.
IE7 and 8)
Force IE9 to fire a form’s oninput when the backspace and delete keys are
pressed inside any of the input nodes.
Force IE9 to fire a form’s oninput when the cut event is fired on any of the input nodes.
here is a link to the commit that adds this support

Categories

Resources