user3057089
user3057089

Reputation:

Removing part of img src

I have 20 images and the same 20 images with a different color called in the same name but the second with a suffix "_blu" -> "google.jpg" and the other one "google_blu.jpg" I would make a Mouseover to change that from one to the other.

I tried like this but i've no idea how to target the image (i can say "every image inside the class .hovertondo)

jQuery(document).ready(function($) {
$(".hovertondo").css("opacity","1");

    $(".hovertondo").hover(function () {
        var src = $(this).attr('src');
        $(this).attr('src', src.replace('_blu', ''));
        $(this).stop().animate({opacity: 0}, "slow");

        },function () {$(this).stop().animate({opacity: 1}, "slow");
                       $(this).attr('src', src.replace('_blu', ''));

        });
});

HTML

<div class="conttondodentosofia">
<img src="http://studiodentisticocova.com/img/trattamenti/carie_blu.jpg" />
<div class="hovertondo">Carie</div>
</div>

I opened it with firebug and the error is

"TypeError: $(...).attr(...) is undefined" (talking about this line $(this).attr('src', src.replace('_blu', ''));)

Does anyone hep me? :) thanks!

Upvotes: 0

Views: 308

Answers (1)

OlivierH
OlivierH

Reputation: 3890

src is not defined in your mouseleave handler (second parameter of hover method) :

Change this

$(".hovertondo").hover(function () {
        var src = $(this).attr('src');
        $(this).attr('src', src.replace('_blu', ''));
        $(this).stop().animate({opacity: 0}, "slow");

        },function () {$(this).stop().animate({opacity: 1}, "slow");
                       $(this).attr('src', src.replace('_blu', ''));

        });

To

$(".hovertondo").hover(function () {
        var src = $(this).attr('src');
        $(this).attr('src', src.replace('_blu', ''));
        $(this).stop().animate({opacity: 0}, "slow");

        },function () {
        var src = $(this).attr('src');
        $(this).stop().animate({opacity: 1}, "slow");
        $(this).attr('src', src.replace('_blu', ''));

        });

BTW, you are making $(this).attr('src', src.replace('_blu', '')); in both cases. There is a case when you have to add '_blu' to your src. It would give something like that : $(this).attr('src', src.replace('.jpg', '_blu.jpg'));

EDIT

You can have a smooth image modification by using fadeOut method :

$('this').fadeOut(300, function(){
      $(this).attr('src', src.replace('_blu', '')).bind('onreadystatechange load', function(){
         if (this.complete) $(this).fadeIn(300);
      });
   });

Upvotes: 1

Related Questions