Change state of the button when pressed/released

Problem

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


$("#appGrid" + catVal.id).append($(ItemsToAdd));
$("#appGrid" + catVal.id).trigger("create");    

$("#appGrid" + catVal.id + " > #" + appVal.id + " > #" + appVal.id ).bind('click', function ()
{
    updateAppInfo(appVal.id);
});

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

Solution

Try adding this:

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

// bind the events
$('.custom-button').bind({
    '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

Discussion

There is currently no discussion for this recipe.

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