jquery - change image src with .replace

4.5k views Asked by At

I've got some images that I want to change to another image when I hover over a div. Image 1: "geluid1", image 2: "geluid2".

$(".block").mouseover(function(){
  $("img",this).attr("src").replace("1","2");
});

But for some reason this doesn't seem to work properly. Can someone help me find the problem?

2

There are 2 answers

0
Tushar On BEST ANSWER

Your code just get the src of the image and replaced the content. However, it did not updated the src attribute of the img.

You didn't set the src attribute value of the img. Use the following code to set the src value to the replaced one.

$("img",this).attr("src", $('img', this).attr('src').replace("1","2"));

CODE

$(".block").mouseover(function() {
    var img = $('img', this); // Cache image object

    img.attr('src', img.attr('src').replace('1', '2'));
    // Update the image src URL to the new URL
});
0
depperm On

You need to put what your replacing inside the parenthesis

$(".block").mouseover(function(){
  var img=$("img",this).attr("src");
  $("img",this).attr("src",img.replace("1","2"));
});