Question

Hi i'm making hybrid app with JQM. I want to add class when i am pressing or tapping(Holding) the button .

Here is my codes...

<a href='btnWhite on'>button</a>

CSS

.btnWhite { background:gray }
.btnWhite.on { background:black }

jQuery Mobile

$('.btnWhite').bind('touchstart', function() {
 $(this).addClass("on");
});

$('.btnWhite').bind('touchend', function() {
 $(this).removeClass("on");
});
Was it helpful?

Solution

Working example: http://jsfiddle.net/Gajotres/LvhdG/

In this example I have used vmousedown, vmouseup and vmousecancel events so I can test it on desktop / mobile devices alike. Just replace them with touchstart, touchend and touchcancel if you want, but it will also work with vmouse events.

HTML :

<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
        <!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
        <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>    
    </head>
    <body>
        <div data-role="page" id="index">
            <div data-theme="b" data-role="header">
                <h1>Index page</h1>
            </div>

            <div data-role="content">
                <a data-role="button" class="btnWhite">button</a>
            </div>
        </div>    
    </body>
</html>   

Javascript :

$(document).on('pagebeforeshow', '#index', function(){ 
    $(document).on('vmousedown','.btnWhite' ,function(){
        $(".btnWhite").addClass('on');
    }).on('vmouseup', function(){
        $(".btnWhite").removeClass('on');
    }).on("vmousecancel", function() {
        $(".btnWhite").removeClass('on');
     }); 
});

CSS :

.btnWhite { 
    background:gray !important;
}
.on { 
    background:black !important; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top