I have an image, and using jQuery I've turned it into a button. The so called button has two states: regular and pushed.
Using jQuery I detect a "mousedown" and "mouseup" and replace the "src" attribute, like so:
$("#btn").click(function() {
;//DO SOMETHING HERE WHEN PRESSED
});
$("#btn").mousedown(function() {
$(this).attr({ src: regular.png });
});
$("#btn").mouseup(function() {
$(this).attr({ src : pushed.png });
});
While testing this offline it works great! But today I noticed that when the images are stored on the server it loads the images over and over and over again with every attribute change.
How can avoid this load issue and make all the images load only once from the server?
Also, if there is a better to accomplish what I'm trying to do here, please let me know.
Thank you.
Create a single image containing both button states. Then, dynamically change the position of the background image on mouseout/mouseover:
<style type="text/css">
.button_normal {
width: 50px;
height: 50px;
background-image: url(merged_button_bg.png);
background-repeat: no-repeat;
border: solid black 1px;
cursor: pointer;
}
.button_over {
background-position: -50px;
}
</style>
<div class="button_normal"></div>
<script>
$(document).ready(function() {
$('.button_normal').mouseover(function() {
$(this).addClass('button_over');
});
$('.button_normal').mouseout(function() {
$(this).removeClass('button_over');
});
});
</script>
This example assumes a target image of 50px square and merged_button_bg.png
is 100px by 50px.