Reputation: 65
I have a code that will change the image upon clicking on the image. However, since I am using mouseup/mousedown, is there a way to make it so that it also work in mobile browsers as well?
$(document).ready(function(){
$(".menulink").eq(0).mouseup(function(){
$('#menu1').attr('src', 'http://placehold.it/333/3ef/img/picture2.jpg');
});
$(".menulink").eq(0).mousedown(function(){
$('#menu1').attr('src', 'http://placehold.it/333/fe3/img/picture1.jpg');
});
$(".menulink").eq(1).mouseup(function(){
$('#menu2').attr('src', 'http://placehold.it/333/3ef/img/picture2.jpg');
});
$(".menulink").eq(1).mousedown(function(){
$('#menu2').attr('src', 'http://placehold.it/333/fe3/img/picture1.jpg');
});
});
Here is the fiddle page
Upvotes: 0
Views: 985
Reputation: 16369
Yes, you need to use touchstart
and touchend
. I also made this slightly more efficient, hope you don't mind.
$(function(){
var $menulink = $('.menulink'),
$menu1 = $('#menu1'),
$menu2 = $('#menu2');
function setSrc($menu,$src){
$menu.src = $src;
}
$menulink.eq(0).on({
'mouseup touchstart':function(){
setSrc($menu1[0],'http://placehold.it/333/3ef/img/picture2.jpg');
},
'mousedown touchend':function(){
setSrc($menu1[0],'http://placehold.it/333/3ef/img/picture1.jpg');
}
});
$menulink.eq(1).on({
'mouseup touchstart':function(){
setSrc($menu2[0],'http://placehold.it/333/3ef/img/picture2.jpg');
},
'mousedown touchend':function(){
setSrc($menu2[0],'http://placehold.it/333/3ef/img/picture1.jpg');
}
});
});
This might be even more efficient, and is especially helpful if you have more than just the two.
$(function(){
var $menulink = $('.menulink');
for(i=$menulink.length;i--;){
var $menu = $('#menu'+(i+1))[0];
$menulink.eq(i).on({
'mouseup touchstart':function(){
$menu.src = 'http://placehold.it/333/3ef/img/picture2.jpg';
},
'mousedown touchend':function(){
$menu.src = 'http://placehold.it/333/3ef/img/picture1.jpg';
}
});
}
});
Just another option to consider.
Upvotes: 2
Reputation: 1831
To add to @Jonathan's answer, also checkout https://github.com/furf/jquery-ui-touch-punch which applies the touch events to their mouse counterparts.
Upvotes: 0