Change state of the button when pressed/released


I am developing a mobile website. I have created dynamic buttons in java-script. Now I want to bind two events with each button.

1) when pressed, change background image of the button to img-pressed.jpg. Note: Every button has its own normal and pressed image source.

2) when clicked, do something.

I am very much confused to work with these two events together.

    ItemsToAdd += '" id="'+ +'">\
               <a id="' + + '" data-role="button" style="background-image:url('+ img_path + appVal.big_icon_normal_path +')" class="custom-button" href="#"></a>\
               <p><br><b>' + + ' </b><br> ' + appVal.apptypename + '<br><i>' + appVal.price + '</i></p> </div>';

$("#appGrid" +$(ItemsToAdd));
$("#appGrid" +"create");    

$("#appGrid" + + " > #" + + " > #" + ).bind('click', function ()

The code is working fine on the click event. Actually i am changing some content on the button click. Now i want to change the source of the image when pressed and change to source to normal when press is released. Content change should also work with it.

I will appreciate you help. Thanks in advance.

Problem courtesy of: naki


Try adding this:

// preload the image
var preloader = new Image();
preloader.src = img_path + appVal.big_icon_mousedown_path;

// bind the events
    'mousedown' : function() {
            // you'll need to set appVal.big_icon_mousedown_path or similar 
            $(this).css('background-image', 'url('+ img_path + appVal.big_icon_mousedown_path +')');
    'mouseup mouseleave' : function() {
            $(this).css('background-image', 'url('+ img_path + appVal.big_icon_normal_path +')');
Solution courtesy of: Josh Harrison


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.