Javascript : onHashchange Test - javascript

I'm trying to check if the browser supports onHashChange or not to hide some code from it if not, in this way:
if(window.onhashchange){
...code...
} else {
...other code...
}
I tried this too:
if(typeof window.onhashchange === "function"){
alert("Supports");
} else {
alert("Doesn't Supports");
}
As described on Quirksmode this should work but if I do an alert for example in true state in Safari than alerts me but Safari is not supporting onHashChange :S
What's the problem with it? If I'm not on the right way how should I check it?

You can detect this event by using the in operator:
if ("onhashchange" in window) {
//...
}
See also:
onhashchange - MDC
Detecting event support without browser sniffing
Emulating onhashchange without setInterval

Be warned that you're better off using feature detection rather than existence inference (such as "onhashchange" in window).
#xkit explained to me a good feature test to work around the fact that although IE7 doesn't support onhashchange it would still return true for existence inference such as if("onhashchange" in window){/code/} when using IE7 Standard Document Mode in IE8.
What #xkit suggested was setting a flag (such as var isSet = true;) within a handler function for the onhashchange event. Then changing window.location.hash using JavaScript and see if the flag was set.

It's likely that the version of Safari that you're using has added support for the onhashchange event since the time that that Quirksmode article was written. Tests should still be valid; try it in other browsers you know not to support the event.
Edit: also, you should use the method described by #CMS instead, as the event will not contain a function by default; thus both of those tests will fail.

if (window.onhashchange !== undefined) alert('Supports onhashchange');

Related

Why is event.defaultPrevented undefined?

As per the MDN docs, a click event should have a property called preventedDefault: https://developer.mozilla.org/en-US/docs/Web/API/Event/defaultPrevented
However, in my code, defaultPrevented is undefined (Chrome and Safari). Instead there is another property called: isDefaultPrevented which seems to do the trick, however, this does not work in iOS Safari.
$('a').click(function(event) {
event.isDefaultPrevented; // returns true in Chrome (if event.preventDefault() was called)
event.defaultPrevented; // the "correct" way to do it as per MDN docs, however, it doesn't work in Chrome nor iOS.
});
This is the way to do it, if you're using jQuery.
$('a').click(function(event) {
event.originalEvent.defaultPrevented; // aparently jQuery will alter the event property, but it stores everything in 'originalEvent'
});

IE attachEvent call returns true, but handler shows "null"

I have a fairly simple ASP.NET page that renders an HTML input (text box). Within the generated HTML, I attach a handler to several events, including onfocus, onkeypress, and onkeyup. Because this is a solution targeted at a version of IE that does not support addEventListener (situation about which I can do nothing), I am forced to use attachEvent.
A typical call to attachEvent is as follows - I've excerpted this source from the original for the sake of brevity/clarity, so it is not precisely the code at issue:
var hostControl = document.getElementById('mytextbox');
var attachResult = hostControl.attachEvent('onfocus', function(){
hostControl.select();
});
if (!attachResult)
{
alert('Attach failed.');
}
attachResult = hostControl.attachEvent('onblur', function(){
if (hostControl.value=='')
{
alert('Warning - no entry.');
}
});
if (!attachResult)
{
alert('Attach failed.');
}
When I step through this code in the IE debugger, attachEvent returns 'true' in both instances, which should indicate that the event attachment attempt was successful. However, when I look at the [Event] handlers for the control within the debugger, all the events show 'null', no handler attached.
Things I've tried/researched:
I've read several different articles on the vagaries of event attachment in IE, so I've speciously avoided any 'this' references.
I tried one version that used one of the addEvent wrapper blocks that tries to use addEventListener if available, even though I knew this would be an IE solution.
When I tried that version against FireFox, event attachment worked properly through addEventListener, but failed in IE using attachEvent (with attachEvent still returning true).
I then opted to eliminate any possible problems the wrapper might be introducing, and used attachEvent directly against the control, which leads me where I am now. The problem persists.
I would like to think I've simply overlooked something very simple, as I've hooked up events before without difficulty, but something here is throwing me a curveball I just don't recognize. Appreciate the extra eyeballs on this to see where I've erred.

Javascript, detect touch devices

I'm using this function to detect if the device is a touch device:
function is_touch_device()
{
return !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
};
Got this function from here: What's the best way to detect a 'touch screen' device using JavaScript?
But since Chrome 25 (25.0.1364) it returns true on my desktop which isn't a touch device.
Also I've updated IE9 to IE10 and it returns true in IE!
Searched around but couldn't find anything useful to fix this except using a something like this: http://detectmobilebrowsers.com/
What do you recommend?
I'm looking forward to your responses!
The code works just fine, the browser is able to understand touch events, just because your screen isn't touchable doesn't mean that the browser doesn't support the functionality. What you are looking to test is a hardware capability which isn't really testable. You can always use different ways though of seeing if the user is actual using a touch interface after touching it once, such as this article describes, or many others that larger libraries use such as Modernizer.
As a reference the code actually used in the article above is:
function isTouchDevice() {
var el = document.createElement('div');
el.setAttribute('ongesturestart', 'return;');
if(typeof el.ongesturestart == "function"){
return true;
}else {
return false
}
}
This seems to work:
function isTouchEnabled() { return !!document.createTouch; }
You could use Modernizr to detect touch capability.
This question is very similar to What's the best way to detect a 'touch screen' device using JavaScript? and should perhaps be considered a duplicate.
i was experiencing a false positive IE10 touch issue as well when I was visiting the site i've been working on from my laptop. The original is_touch_device method, i used basically the same thing. I modified the latter half of that statement to be the following:
function is_touch_device()
{
return !!('ontouchstart' in window) || (!!('onmsgesturechange' in window) && !!window.navigator.maxTouchPoints);
}
window.navigator.maxTouchPoints seems to be something specific in IE10 based on this post: http://msdn.microsoft.com/en-us/library/hh772144(v=vs.85).aspx
You can use 51dergees.mobi for detection on the server appropriately changing page view. It has HasTouchScreen, IsSmartPhone, IsTablet properties etc.

Why is $.browser deprecated - and what is a better alternative?

So I know $.browser has been deprecated and "frowned upon", since jQuery 1.3, but it continues to exist & work in the code.
It's still using the plain javascript: navigator.userAgent to determine the browser being used, as well as the version.
Now is there something about these I don't know about navigator itself, that I shouldn't be using either $.browser or plain vanilla JS to get the browser/version? I just want to make sure when they have IE8 (for example), they really do have it, and I'm not processing the wrong code.
What other alternatives do we have for browser sniffing? I know about $.support, I use modernizr, but sometimes I need just need the down and dirty browser version, instead of seeing what the browser is capable of handling (I think that is a completely different problem solver).
You kind of answer the question yourself. The ideal is to check for feature support. As more browsers and devices come onto the market this approach should scale.
However if you want to do something 'down and dirty' then browser detection of course works, but only so far as you will know your code works in the existing set of browsers (or even just those you've tested your code with).
Generally it's recommended not to try to guess what the browser is but to check if a function is available. There are too many browsers and variants.
To check if a function is available, you simply do this :
if (!Array.prototype.map) {
// not available, shut down computer !
If a "must" to know which browser on the page for me, I use this personally;
(function() {
var re_browsers = {
firefox: /firefox\/([\d\.]+)/,
chrome: /chrome\/([\d\.]+)/,
safari: /webkit.*?version\/([\d\.]+)/,
opera: /opera.*?version\/([\d\.]+)/,
ie: /msie\s+([\d\.]+)/
// ...
};
var ua = window.navigator.userAgent.toLowerCase(), k, re, browser = {};
for (k in re_browsers) {
if (re = re_browsers[k].exec(ua)) {
break;
}
}
browser[k] = true;
browser["version"] = parseFloat(re && re[1]);
browser["versionOrig"] = re[1];
jQuery.extend({browser: browser});
})();

Check browser compatibility for HTML5 History API support?

Is there any way to check a browser whether it supports 'HTML5 History API' using JavaScript.
Do I have to check all the browsers and its versions with a long list of condition in if statement.
Or simply like checking any object of function using 'if' statement is enough???...
Checking for the existence of a pushState() method on the global history object should be sufficient.
function supports_history_api() {
return !!(window.history && history.pushState);
}
For more general HTML 5 feature detection I'd look at Modernizer
http://diveintohtml5.info/detect.html#modernizr
This will insulate your code from the messy specifics of each test, making the code more readable and less error prone. With the Modernizer script on your page you'd just do:
if (Modernizr.history) {
// history management works!
} else {
// no history support :(
// fall back to a scripted solution like History.js
}
Checking for history.pushState and history.replaceState objects existence should be sufficient, as it's generally sufficient with feature detection in general.
You can use canisuse.js script to detect if your browsers supports history or not
caniuse.history()
You can check weather or not a function is registered:
if (typeof history.pushState != 'undefined') {
//Enabled
}
Then just replace //Enabled with whatever you wish to do if it's supported.

Categories