Detect if Hover Exists or Is Available - javascript

Everyone has been pushing towards feature detection for a long time. I'd like to detect if a visitor's browser supports the :hover pseudo class. It's my understanding there are enough, if not most, mobile devices that do not support hovering, so I'd like to gear my event listeners accordingly. But without mobile detection, I'm unsure how to accomplish this, and I've not found anything via Google or SO thus far.
Perhaps something similar to question #8981463
$(function() {
var canHover = $(document).is(":hover");
});
I won't be able to test this on a mobile device 'till next week.
Thoughts?

There is now a well-supported media query to detect whether hover is supported:
https://developer.mozilla.org/en-US/docs/Web/CSS/#media/hover
Which you can use with Window.matchMedia:
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
Then you would use:
if (window.matchMedia( "(hover: none)" ).matches) {
// hover unavailable
}

There is no is(':hover'), you can't detect CSS pseudo classes with javascript as they are not part of the DOM.
You can however detect certain events that are only available on touch screens and act accordingly, modernizer does something like this
if ('ontouchstart' in document.documentElement) {
document.documentElement.classList.add('touch');
} else {
document.documentElement.classList.add('no-touch');
}
where it adds classes to the <html> element that tells you wether or not the device has a touch screen or not, so you can do something like this in CSS
.no-touch .element:hover {color: red;} // for users with a mouse
.touch .element {color: blue;} // for touch devices

Couldn't sleep, and may have figured it out, at least perhaps for my particular situation. I use sprites on these buttons and I'm already doing sprite position checks elsewhere. My thought is when the button is clicked, prior to firing, it can also do the sprite position check. If the sprite hasn't been re-positioned for the clicked button, it would seem it is not a hover-able device, and I can treat the click as the 1st of a 2-part activation. I read earlier today that some mobile devices do that already, in that they treat the 1st click as the hover.
My sprite positioning logic as as such, and perhaps could be called prior to the button's click-fire event:
if ($(elem).css('background-position').indexOf('76px') >= 0 ) {

Related

IE, and iframe.elementFromPoint not passing event

Update: Fiddle Demonstration -- http://jsfiddle.net/7tfbtso6/2/ -- Most of the settings work in chrome and firefox, but the only one that works in IE is Left-align: 105px. I do have overflow set to hidden on html and body, but this makes no difference. IE will not work if the element is not visible on screen. And overflow: visible on html and body give the effect of auto and no effect on the problem here.
My site uses two contentEditable divs.
#rInput is part of the document.
#rSyntax is part of an iframe under (z-index) #rInput.
In every browser I've tried so far, except IE (I'll get to that in a moment.), I'm able to determine what element is contained within the iframe using elementFromPoint().
In IE's case, this is only possible if they're not overlapping which isn't possible because a secondary purpose, as the name implies, is to provide syntax-highlighting.
The IE IFrame has to be visible, on screen, not obstructed by any objects. I've tried display: none;, visibility: hidden, and pushing it down in a div with overflow: hidden, but all of these attempts cause it not to work. I've also tried setting the height and width to small proportions.
If any of these could work, I could use two copies of rSyntax, one on top (z-index), hidden somehow, for mouse events and one for syntax highlighting.
Most of these solutions work in every browser but IE. The IE box simply demands that it be on top.
"Flickering" it with css (display, visibility, pointer-events) seems awfully hacky (and just plain awful). I haven't really tried to implement it because it seems like a last resort.
The problem is further complicated because I'm trying to capture clicks and mouseovers, for different purposes (clicks for finding content, mouseovers for tooltips--created with a div mimicking attr("title").
I've briefly tried placing the iframe on top (z-index) of the div, but there's no way to intercept the clicks and pass to the lower object because it runs in to the same problem.
Here's the script I'm using to get the objects, partly in case it's useful to anyone.
$(document).on("mousemove", "#rInput", function (e) {
$element = $(document.getElementById('frSyntax').contentDocument.elementFromPoint(e.pageX+$("#rInputContainer").scrollLeft()-10,e.pageY+$("#rInputContainer").scrollTop()-12));
if ($element.is("span") && $element.attr("title") && $element.attr("title").length) {
$("#syntip").text($element.attr("title"));
$("#syntip").css({"top": e.pageY+10, "left": e.pageX, "display": "inline-block"});
} else {
$("#syntip").hide();
}
});
I have considered transparency, and that works for this element, because it's small, but I use a similar setup with a large element that takes up more than 50% of the screen, there would be problems.
After many frustrating efforts, I concluded that pushing the top (z-index-wise) element offscreen was the only solution for IE/Edge. Flickering it with display: none causes some properties I needed, like width, to not be accurate.
Just make sure you push it farther than the element will ever be. My application is sidescrolling so I merely needed to place the css top to something like 2000.

Make Html-Custom-Cursor the screen cursor

I'm trying to figure a way to ensure a certain custom css cursor is available for the whole screen. The idea is that when the user clicks mouse down on a div, I'll attach the listeners to the document (move, up) to be able to catch events outside the browser window as well.
However, the custom cursor assigned for mouse down is lost as soon as the user moves out of the div. This doesn't happen in Mozilla when I use element.setCapture as this will also keep the current cursor active until releasing capture. Is there a way to do the same (aka keep cursor active for screen while dragging) for any (modern) browser?
This is a common question. Here is a hack you can do.
CSS:
*{
cursor: pointer;
}
Javascript:
document.onselectstart = function () { return false; };
http://jsfiddle.net/bEgMK/

How to ensure CSS :hover is applied to dynamically added element

I have a script that adds full images dynamically over thumbnails when you hover over them. I've also given the full images a CSS :hover style to make them expand to a larger width (where normally they are constrained to the dimensions of the thumbnail). This works fine if the image loads quickly or is cached, but if the full image takes a long time to load and you don't move the mouse while it's loading, then once it does appear it will usually stay at the thumbnail width (the non-:hover style) until you move the mouse again. I get this behavior in all browsers that I've tried it in. I'm wondering if this is a bug, and if there's a way to fix or work around it.
It may be worth noting that I've also tried to do the same thing in Javascript with .on('mouseenter'), and encountered the same problem.
Due to the nature of the issue, it can be hard to reproduce, especially if you have a fast connection. I chose a largish photo from Wikipedia to demonstrate, but to make it work you might have to change it to something especially large or from a slow domain. Also note that you may have to clear the cache for successive retries.
If you still can't reproduce, you can add an artificial delay to the fullimage.load before the call to anchor.show().
HTML:
<img id="image" src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Cairo_International_Stadium.jpg/220px-Cairo_International_Stadium.jpg" />
CSS:
.kiyuras-image {
position: absolute;
top: 8px;
left: 8px;
max-width: 220px;
}
.kiyuras-image:hover {
max-width: 400px;
}
JS:
$(function () {
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show();
});
var anchor = $('<a/>').hide().append(fullimage);
$('body').prepend(anchor);
$("#image").on('mouseenter', function () {
fullimage.attr('src',fullimageurl);
$(this).off('mouseenter');
});
});
JS Bin
Updated JS Bin with 1.5-second delay added (Hopefully makes issue clearer)
Again: Reproducing the issue involves clearing your cache of the large image, and then hovering over the original image to initial the loading of large image, then not moving your mouse while it's loading. Intended behavior is for the large image to properly take on the :hover pseudo-class when it eventually loads. Issue I see when it takes longer than ~0.75 secs to load is that it does not take on :hover until you jiggle the mouse a little.
Edit: See my comments on #LucaFagioli's answer for further details of my use case.
Edit, the sequel: I thought I already did this, but I just tried to reproduce the issue in Firefox and I couldn't. Perhaps this is a Chrome bug?
Most browsers update their hover states only when the cursor moves over an element by at least one pixel. When the cursor enters the thumbnail's img it gets hover applied and runs your mouseenter handler. If you keep your cursor still until the full-sized image loads, your old img (the thumbnail) will keep the hover state and the new one won't get it.
To get it working in these browsers, move the hover pseudo-class to a common parent element in the CSS; for example, enclose both imgs in a span.
If the selectors are correct, CSS will be applied to all elements, dynamic or otherwise. This includes all pseudo classes, and will change as attributes in the DOM change.
[Edit: while my explanation might be of interest, pozs' solution above is nicer, so I suggest using that if you can.]
The hover pseudo-class specification is quite relaxed concerning when it should be activated:
CSS does not define which elements may be in the above states,
or how the states are entered and left. Scripting may change
whether elements react to user events or not, and different
devices and UAs may have different ways of pointing to, or
activating elements.
In particular, it is not being activated when you update the visibility of the anchor element on load.
You can get around this fairly easily: copy the hover styles to a class, intercept the cursor moving over the element that it will eventually cover, and based on that add or remove your class from the element.
Demo: JS Bin (based on your delayed example).
Javascript:
$("#image")
.on('mouseenter', function () {
fullimage.attr('src',fullimageurl).toggleClass('mouseover', true);
$(this).off('mouseenter');
})
.mouseleave(function() {
fullimage.toggleClass('mouseover', false);
});
CSS:
.kiyuras-image:hover, .kiyuras-image.mouseover {
max-width: 400px;
}
TL;DR: You cannot rely on :hover applying to dynamically added elements underneath the cursor. However, there are workarounds available in both pure CSS and Javascript.
I'm upvoting both Jordan Gray and posz' answers, and I wish I could award them both the bounty. Jordan Gray addressed the issue re: the CSS specification in a somewhat conclusive way and offered (another) working fix that still allowed for :hover and other CSS effects like transitions, except on load. posz provided a solution that works even better and avoids Javascript for any of the hover events; I provide essentially the same solution here, but with a div instead of a span. I decided to award it to him, but I think Jordan's input was essential. I'm adding and accepting my own answer because I felt the need to elaborate more on all of this myself. (Edit: Changed, I accepted posz')
Jordan referenced the CSS2 spec; I will refer instead to CSS3. As far as I can tell, they don't differ on this point.
The pseudo-class in question is :hover, which refers to elements that the user has "designated with a pointing device." The exact definition of the behavior is deliberately left vague to allow for different kinds of interaction and media, which unfortunately means that the spec does not address questions like: "Should a new element that appears under the pointing device have this pseudo-class applied?" This is a hard question to answer. Which answer will align with user intent in a majority of cases? A dynamic change to a page the user is interacting with would normally be a result of ongoing user interaction or preparation for the same. Therefore, I would say yes, and most current browsers seem to agree. Normally, when you add an element under the cursor, :hover is immediately applied. You can see this here: The jsbin I originally posted. Note that if there's a delay in loading the larger image, you may have to refresh the page to get it to work, for reasons I'll go into.
Now, there's a similar case where the user activates the browser itself with the cursor held stationary over an element with a :hover rule; should it apply in that case? The mouse "hover" in this case was not a result of direct user interaction. But the pointing device is designating it, right? Besides, any movement of the mouse will certainly result in an unambiguous interaction. This is a harder question to answer, and browsers answer it in different ways. When you're activating them, Chrome and Firefox do not change :hover state until you move the mouse (Even if you activated them with a click!). Internet Explorer, on the other hand, updates :hover state as soon as it's activated. In fact, it updates it even when it's not active, as long as it's the first visible window under the mouse. You can see this yourself using the jsbin linked above.
Let's return to the first case, though, because that's where my current issue arises. In my case, the user hasn't moved the mouse for a significant length of time (over a second), and an element is added directly underneath the cursor. This could more easily be argued to be a case where user interaction is ambiguous, and where the pseudo-class should not be toggled. Personally, I think that it should still be applied. However, most browsers do not seem to agree with me. When you hover over the image for the first time and then do not move your mouse in this jsbin (Which is the one I posted in my question to demonstrate the issue, and, like the first one, has a straightforward :hover selector), the :hover class is not applied in current Chrome, Opera, and IE. (Safari also doesn't apply it, but interestingly, it does if you go on to press a key on the keyboard.) In Firefox, however, the :hover class is applied immediately. Since Chrome and Firefox were the only two I initially tested with, I thought this was a bug in Chrome. However, the spec is more or less completely silent on this point. Most implementations say nay; Firefox and I say aye.
Here are the relevant sections of the spec:
The :hover pseudo-class applies while the user designates an element with a pointing device, but does not necessarily activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not that do not support interactive media do not have to support this pseudo-class. Some conforming user agents that support interactive media may not be able to support this pseudo-class (e.g., a pen device that does not detect hovering).
[...]
Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.
[...]
Note: If the ‘:hover’ state applies to an element because its child is designated by a pointing device, then it's possible for ‘:hover’ to apply to an element that is not underneath the pointing device.
So! On to the workarounds! As several have zealously pointed out in this thread, Javascript and jQuery provide solutions for this as well, relying on the 'mouseover' and 'mouseenter' DOM events. I explored quite a few of those solutions myself, both before and after asking this question. However, these have their own issues, they have slightly different behavior, and they usually involve simply toggling a CSS class anyway. Besides, why use Javascript if it's not necessary?
I was interested in finding a solution that used :hover and nothing else, and this is it (jsbin). Instead of putting the :hover on the element being added, we instead put it on an existing element that contains that new element, and that takes up the same physical space; in this case, a div containing both the thumbnail and the new larger image (which, when not hovered, will be the same size as the div and thumbnail). This would seem to be fairly specific to my use case, but it could probably be accomplished in general using a positioned div with the same size as the new element.
Adding: After I finished composing this answer, pozs provided basically the same solution as above!
A compromise between this and one of the full-Javascript solutions is to have a one-time-use class that will effectively rely on Javascript/DOM hover events while adding the new element, and then remove all that and rely on :hover going forward. This is the solution Jordan Gray offered (Jsbin)
Both of these work in all the browsers I tried: Chrome, Firefox, Opera, Safari, and Internet Explorer.
From this part of your question: "This works fine if the image loads quickly or is cached, but if the full image takes a long time to load and you don't move the mouse while it's loading,"
Could it be worth while to "preload" all of the images first with JavaScript. This may allow all of the images to load successfully first, and it may be a little more user friendly for people with slower connections.
You could do something like that : http://jsfiddle.net/jR5Ba/5/
In summary, append a loading layout in front of your image, then append a div containing your large image with a .load() callback to remove your loading layer.
The fiddle above has not been simplified and cleaned up due to lack of time, but I can continue to work on it tomorrow if needed.
$imageContainer = $("#image-container");
$image = $('#image');
$imageContainer.on({
mouseenter: function (event) {
//Add a loading class
$imageContainer.addClass('loading');
$image.css('opacity',0.5);
//Insert div (for styling) containing large image
$(this).append('<div><img class="hidden large-image-container" id="'+this.id+'-large" src="'+fullimageurl+'" /></div>');
//Append large image load callback
$('#'+this.id+'-large').load(function() {
$imageContainer.removeClass('loading');
$image.css('opacity',1);
$(this).slideDown('slow');
//alert ("The image has loaded!");
});
},
mouseleave: function (event) {
//Remove loading class
$imageContainer.removeClass('loading');
//Remove div with large image
$('#'+this.id+'-large').remove();
$image.css('opacity',1);
}
});
EDIT
Here is a new version of the fiddle including the right size loading layer with an animation when the large picture is displayed : http://jsfiddle.net/jR5Ba/6/
Hope it will help
Don't let the IMG tag get added to the DOM until it has an image to download. That way the Load event won't fire until the image has been loaded. Here is the amended JS:
$(function () {
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show(); // Only happens after IMG src has loaded
});
var anchor = $('<a/>').hide();
$('body').prepend(anchor);
$("#image").on('mouseenter', function () {
fullimage.attr('src',fullimageurl); // IMG has source
$(this).off('mouseenter');
anchor.append(fullimage); // Append IMG to DOM now.
});
});
I did that and it worked on Chrome (version 22.0.1229.94 m):
I changed the css as that:
.kiyuras-image{
position: absolute;
top: 8px;
left: 8px;
max-width: 400px;
}
.not-hovered{
max-width: 220px;
}
and the script this way:
$(function(){
var fullimageurl = 'http://upload.wikimedia.org/wikipedia/commons/3/32/Cairo_International_Stadium.jpg';
var fullimage = $('<img/>')
.addClass('kiyuras-image')
.load(function () {
anchor.show();
});
var anchor = $('<a/>').hide().append(fullimage);
$('body').prepend(anchor);
$('.kiyuras-image').on('mouseout',function(){
$(this).addClass('not-hovered');
});
$('.kiyuras-image').on('mouseover',function(){
$(this).removeClass('not-hovered');
});
$("#image").one('mouseover', function(){
fullimage.attr('src',fullimageurl);
});
});
Basically I think it's a Chrome bug in detecting/rendering the 'hover' status; in fact when I tried to simply change the css as:
.kiyuras-image{
position: absolute;
top: 8px;
left: 8px;
max-width: 400px;
}
.kiyuras-image:not(:hover) {
position: absolute;
top: 8px;
left: 8px;
max-width: 220px;
}
it still didn't worked.
PS: sorry for my english.
I'm not 100% sure why the :hover declaration is only triggered on slight mouse move. A possible reason could be that technically you may not really hover the element. Basically you're shoving the element under the cursor while it is loading (until the large image is completely loaded the A element has display: none and can therefore impossible be in the :hover state). At the same time, that doesn't explain the difference with smaller images though...
So, a workaround is to just use JavaScript and leave the :hover statement out of the equation. Just show the user the two different IMG elements depending on the hover state (toggles in JavaScript). As an extra advantage, the image doesn't have to be scaled up and down dynamically by the browser (visual glitch in Chrome).
See http://jsbin.com/ifitep/34/
UPDATE: By using JavaScript to add an .active class on the large image, it's entirely possible to keep using native CSS animations. See http://jsbin.com/ifitep/48

Invisible elements don't receive mouse events

I'm writing a swatch picker in jquery for a site that allows you to specify a colour for a seat cover. The picker consists of a grid of thumbnail images, when the user mouses over each of these thumbnails, a bigger image is shown over the top.
Now the thing is, the client wants the images that are partially or totally obscured by the overlying bigger image to still respond to events.
My solution to this problem was to add a preview element for showing the bigger picture to the list with a z-index of 5. Then I'd clone the original set of elements in the swatch list and overlay them as invisible elements with a z-index of 10. The result is that the partially obscured elements appear to still respond to mouse events, though in actuality the underlying elements don't have events attached. The events are actually attached to invisible elements in front of the preview element (I hope that makes sense!).
My first attempt to achieve this effect was for the cloned elements to get a visibility: hidden CSS style, but these don't respond to mouse events. I tried using empty elements with background: transparent instead, and this seemed to work fine, but testing in IE9 revealed that these elements don't respond to mouse events either!
I can get it to work if I remove the background:transparent style from the overlay elements, bot of course now they obscure everything underneath.
It only seems to be IE9 that has this issue so far. IE8 appeared to trigger the events on transparent items fine. It also seems to work as intended in FireFox and Chrome.
The solution in the end was annoyingly simple. All that was needed was to give the invisible elements the following styling:
background-color: white;
opacity: 0;
filter: alpha(opacity=0); /* for old IE versions */
This leaves the elements invisible, but still responsive to mouse events.
I would use a double binding technique for this, where the mouseover is bound to the behind image, and the out is bound to the front image. that allows you to have the front image hidden until the behind image is hovered.
// use $.fn.each so that each thumb gets its own timer.
$(".thumb-behind").each(function(){
var timer;
$(this).hover(function(){
$(this).next().stop(true,true).fadeIn();
},function(){
timer = setTimeout(function(){
$(this).next().stop(true,true).fadeOut();
},10);
});
$(this).next().hover(function(){
clearTimeout(timer);
},function(){
$(this).stop(true,true).fadeOut();
});
});
just make sure you modify $(this).next() to select the larger thumbnail in relation to the current thumbnail.

Safari iphone/ipad "mouse hover" on new link after prior one is replaced with javascript

After you click a link on the iphone or ipad, it leaves a simulated mouse hover that triggers the a:hover css styling on that link. If the link has a javascript handler that keeps you on same page, the hover state will not change until you click on another link.
This gets weird if you have an ajax widget that asks questions and each answer is link. When you touch one of the answers, it highlights with the hover state, and then when the question and answers are replaced (using javascript) by a new question and answers, the new answer that appears in the same position as the prior answer has its hover state automatically triggered. I want to prevent that from happening to the new answer link.
Is there any way (maybe some something in javascript) that can give me the same result as the "hover" no longer being above this element?
Notes:
I know I could just have a:hover use the same css styling as a, but a:active styling is hardly noticeable since the active state of a touch click is so brief, so I'm hoping for something that can show the hover state on a link until I replace it with new html
I have tried a variety of approaches in javascript, like calling "blur()" on the dom element and some other stuff, but no luck—I'm starting to think that the best solution is to apply classes to the links on javascript events to manage the hover state myself (or just leave it as it is)
The problem is that when you replace the content in place, Mobile Safari treats the new elements as if they were the old ones, because they occupy the same position in the DOM. One workaround is to remove the old elements first, then add the new elements asynchronously. The simplest way to do this is using setTimeout().
http://jsfiddle.net/chad/JNZvu/10/
// When we click on an answer
$('body').on('click', '.answer', function(){
// don't follow it's link
event.preventDefault();
// fade out the container
$('.container').fadeOut(function(){
// remove old elements (happens after fadeOut because we are in the callback)
$('.container').html('');
// add new elements asynchronously and fade container back in.
setTimeout( '$(\'.container\').html(\'<a class="answer" href="#c">link 3</a><a class="answer" href="#d">link 4</a>\');$(\'.container\').fadeIn();', 0);
});
});
When doing this for real, the fadeOut would be called at the same time as the AJAX function, and then the removal/addition would happen in the AJAX callback.
You can try writing another :hover rule that activates when the parent has a particular class, in effect negating the existing hover rule. The class on the parent would need to be added on touchend and removed on touchstart, so that the default rule could take effect on the next link clicked or touched.
I just solved a similar problem where I want hover styling for list items, but since the parent can scroll with one finger using iscroll, I need to cancel that hover effect as soon as the scroll list moves. It's using jQuery, but you get the idea:
$('ul.scroll').bind('touchmove', function(e) {
$(this).addClass('moving');
});
$('ul.scroll').bind('touchstart', function(e) {
$(this).removeClass('moving');
});
here are my style rules:
ul.scroll li:hover {
background-color: #D1E8DA;
}
ul.scroll.moving li:hover {
background-color: #EFEFEF;
}

Categories

Resources