1

So I have an un-pushed and a pushed button image. I want the website to show the un-pushed image. When the user clicks the button, it shows the pushed button image and then goes back to the un-pushed image when they release the click.

HTML

<div class="button"></div>

CSS

.button{
background-image: url("images/btn-unclicked.png");
width:210px;
height:210px;}

jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(function() {
$('.button').click(function() {
$(this).css('background-image', 'url(/images/btn-clicked.png)');
});
}):
</script>`

And then when the user releases the click it should go back to the image btn-unclicked. The above code is not working. I realize I have nothing for it to go back to the original image when the click is released - but not even the first part where it initially changes the image is working.

4
  • 2
    Why not just use CSS? .button:active {...} Commented Dec 17, 2014 at 20:37
  • 3
    are you sure your image path is correct? It says url("images/btn-unclicked.png") in css and url(/images/btn-clicked.png) in js Commented Dec 17, 2014 at 20:37
  • 1
    Definitely use CSS for this. Commented Dec 17, 2014 at 20:39
  • See I originally assumed it was a simple CSS solution. Then when I went to look it up I Googled "change background image on click" and the top 3 results were stack overflow questions that involved jQuery... Works like a charm though, thank you. Commented Dec 17, 2014 at 20:42

3 Answers 3

1

The solution was simply using the .button:active class in CSS instead of jQuery.

Sign up to request clarification or add additional context in comments.

Comments

1

You are using the click() mouse event, which as you noted executes every time the mouse button is pressed and released.

I would recommend isherwood's comment as the best method of getting the effect you intend, but if you wish to use jQuery, there are built-in mouse events that handle what you are talking about:

mousedown() is sent when you click down with the mouse.

mouseup() is sent when you release the click.

Hope that helps.

Comments

0
.button {
    background: url(http://placehold.it/80x50);
}
.button:active {
    background: url(http://placehold.it/80x50/ff0000);
}

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.