loriensleafs loriensleafs - 6 months ago 36
Javascript Question

jquery preventing hover function on touch

I have a hover function, if it's a touch device I'd like the hover event to NOT happen. The problem is when you tap the link with a touch device it does the hover event before doing the click event, so you have to tap it twice for it to work.

this is the hover function:

$("#close").hover(
function () {
$("#close_2").css({
display: "none"
});
$("#close_1").css({
display: "block"
});
},
function () {
$("#close_1").css({
display: "none"
});
$("#close_2").css({
display: "block"
});;
}
);


and then I have this set up as the click function:

$('#close').click(function() {
var id = $(this).attr('id');
$('#full_image').animate({
height: 0
}, 300, function() {
$('#full_image img').attr('src','#');
});
$("#close_1").css({
display: "none"
});
$("#close_2").css({
display: "none"
});
$("#close").css({
display: "none"
});
});

Answer

ended up using touch detection:

var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);

if(agentID) { 
    $('#close').click(function() {
        var id = $(this).attr('id');
        $('#full_image').animate({
            height: 0
        }, 300, function() {
            $('#full_image img').attr('src','#');
        });
        $("#close_1").css({
            display: "none"
        });
        $("#close_2").css({
            display: "none"
        });
        $("#close").css({
            display: "none"
        });
    });
}
else {
    $('#close').hover(
        function() {
            $("#close_2").css({
                display: "none"
            });
            $("#close_1").css({
                display: "block"
            });
        }, function() {
            $("#close_1").css({
                display: "none"
            });
            $("#close_2").css({
                display: "block"
            });
        }
    ); 
    $('#close').click(function() {
        var id = $(this).attr('id');
        $('#full_image').animate({
            height: 0
        }, 300, function() {
            $('#full_image img').attr('src','#');
        });
        $("#close_1").css({
            display: "none"
        });
        $("#close_2").css({
            display: "none"
        });
        $("#close").css({
            display: "none"
        });
    });
}