jch02140
jch02140

Reputation: 65

Image change onclick not work in mobile browser

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

Answers (3)

PlantTheIdea
PlantTheIdea

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

Jonathan
Jonathan

Reputation: 9151

Edit: don't use click

Yes, you use touchstart and touchend.

Upvotes: 0

mitch
mitch

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

Related Questions