Nick Suy
Nick Suy

Reputation: 3

jquery - change image src with .replace

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?

Upvotes: 0

Views: 4658

Answers (2)

Tushar
Tushar

Reputation: 87233

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
});

Upvotes: 2

depperm
depperm

Reputation: 10756

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"));
});

Upvotes: 0

Related Questions