Jquery hover function and click through on tablet

感情迁移 提交于 2019-11-29 08:51:32

UPDATE: after recently resorting to using this script again, I realized things can be done a lot simpler, not requiring any flags at all.

See revised code on my website.

Original answer:

Had the exact same issue today. I solved it using the data attribute, live bound to a touchstart event (which is a basic touch-device check, but you could make this more thorough). Try using the following code, replacing the 'clickable_element' to suit your needs.

$('clickable_element').live("touchstart",function(e){
    if ($(this).data('clicked_once')) {
        // element has been tapped (hovered), reset 'clicked_once' data flag and return true
        $(this).data('clicked_once', false);
        return true;
    } else {
        // element has not been tapped (hovered) yet, set 'clicked_once' data flag to true
        e.preventDefault();
        $(this).trigger("mouseenter"); //optional: trigger the hover state, as preventDefault(); breaks this.
        $(this).data('clicked_once', true);
    }
});

This should stop the tablet from activating the link on the first tap, activating it on the second tap.

Edit: in case of multiple link elements, which need to be 'reset' when one of the other elements are clicked, try attaching the data attribute to the parent container:

The HTML:

<div id="parent-element">
    <a href="" id="1">Link 1</a>
    <a href="" id="2">Link 2</a>
    <a href="" id="3">Link 3</a>
</div>

jQuery:

$('#parent-element a').live("touchstart",function(e){
    var $link_id = $(this).attr('id');
    if ($(this).parent().data('clicked') == $link_id) {
        // element has been tapped (hovered), reset 'clicked' data flag on parent element and return true (activates link)
        $(this).parent().data('clicked', null);
        return true;
    } else {
        // element has not been tapped (hovered) yet, set 'clicked' data flag on parent element to id of clicked link, and prevent click
        e.preventDefault(); // return false; on the end of this else statement would do the same
        $(this).trigger("mouseenter"); //optional: trigger the hover state, as preventDefault(); breaks this. I do suggest adding a class with addClass, as this is much more reliable.
        $(this).parent().data('clicked', $link_id);
    }
});

I wish I could reply to the original post, but to reset the 'clicked_once' state, you should be able to use this bit from your original code

$(".image_thumb ul li").removeClass('clicked_once');

(or something like it) at the outset of the else statement of c_kick's code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!