I have a simple menu with images. The image source changes depending on viewer's action (mouseover, click, nothing). I am having trouble to reset the non-active images source to default when another image is clicked?
(on-click) button1S.jpg -> button1S_active.jpg
I have tried to use .not(this).replace, but I get an error according to chrome "Cannot read property 'replace' of undefined".
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
</head>
<body>
<img class="logo" src="logo.jpg"><br>
<img class="menu_btn" src="button1S.jpg"><br>
<img class="menu_btn" src="button2S.jpg"><br>
<img class="menu_btn" src="button3S.jpg"><br>
<img class="menu_btn" src="button4S.jpg">
</body>
<script>
$("img.menu_btn").hover(
function () {
this.src = this.src.replace('.jpg', '_hover.jpg');
$(this).addClass('hovered');
},
function () {
this.src = this.src.replace('_hover.jpg', '.jpg');
$(this).removeClass('hovered');
});
$('img.menu_btn').click(
function () {
var unactive = $('img.menu_btn').not(this);
unactive.src = unactive.src.replace('_active.jpg', '.jpg'); //without this, it works but _active.jpg isn't removed when unactive.
unactive.removeClass("active");
$(this).addClass('active');
this.src = this.src.replace('_hover.jpg', '_active.jpg');
alert(this.src);
});
Thank you very much.
the problem is
unactive
is a jQuery object not a dom element referenceFollowing on from my comment, you can replace all this "modification of image URLs" using just a single class and a technique known as "sprites".
A sprite is basically an image file that contains multiple pictures. The one used in my JSFiddle looks like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7v1L2yqd/2/
You reference them by changing the image offsets in the style. In my example it simply adds and removes a
hover
style, which in the CSS styling causes the background image to be offset.CSS:
Handy reference here: http://www.w3schools.com/css/css_image_sprites.asp
If the sprite contained all your icons, you would offset them to their base image, and the .hover class would just move the horizontal position: