i've got a problem I need help with.
I am trying to create a mouseover animation using jQuery so that when a user hover over an image it shows a highlighted version of the image. I know I can do this with CSS, the problem is however that the content needs to be managed. So i wanted to write a function that matches a part of the image filename and use a wildcard for the rest of the filename.
Here is the HTML: This is the image that will always be shown unless a user hover over the image.
<img class="imgPath" src="<?php echo PATH_SITE. 'uploads/folder/bgr_img.jpg' ?>" alt="First Image" />
When the user hover over the image, I would like to change the src:
<img class="imgPath" src="<?php echo PATH_SITE. 'uploads/folder/hvr_image.jpg' ?>" alt="First Image" />
On mouseout I would like the src to return to its previous state "bgr_image.jpg"
This is the jQuery I am using currently:
$(function() {
$(".imgPath")
.mouseover(function() {
var src = $(this).attr("src").match("http://domain.com/path/to/img/hvr_image.jpg");
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("http://domain.com/path/to/img/hvr_image.jpg", "http://domain.com/path/to/img/bgr_image.jpg");
$(this).attr("src", src);
});
});
If I hover over the image right now, it will change the src to "null". I tried to use the path name without the domain included but it returns the same value.
Help would be much appreciated.
Why do you match your src or replace it? Just change it:
$(function() {
$(".imgPath").hover(
function() { $(this).attr("src", "http://domain.com/path/to/img/hvr_image.jpg"); },
function() { $(this).attr("src", "http://domain.com/path/to/img/bgr_image.jpg"); }
);
});
EDIT:
match() returns an array of the matches: Access your src with [0]
$(function() {
$(".imgPath")
.mouseover(function() {
var src = $(this).attr("src").match("http://domain.com/path/to/img/hvr_image.jpg");
$(this).attr("src", src[0]);
})
.mouseout(function() {
var src = $(this).attr("src").replace("http://domain.com/path/to/img/hvr_image.jpg", "http://domain.com/path/to/img/bgr_image.jpg");
$(this).attr("src", src);
});
});
EDIT2:
<img class="imgPath" onmouseover="changeImgSrc(this, '<?php echo PATH_SITE. 'uploads/folder/hvr_image.jpg' ) ?>'" onmouseout="changeImgSrc(this, '<?php echo PATH_SITE. 'uploads/folder/bgr_image.jpg' ) ?>'" src="<?php echo PATH_SITE. 'uploads/folder/bgr_image.jpg' ?>" alt="FirstImage" />
<script>
function changeImgSrc(img, imgsrc) {
$(img).attr('src', imgsrc);
}
</script>
OR:
<img class="imgPath" onmouseover="this.src = '<?php echo PATH_SITE. 'uploads/folder/hvr_image.jpg' ) ?>'" onmouseout="this.src = '<?php echo PATH_SITE. 'uploads/folder/bgr_image.jpg' ) ?>'" src="<?php echo PATH_SITE. 'uploads/folder/bgr_image.jpg' ?>" alt="FirstImage" />