silvith
silvith

Reputation: 290

My image swap in jquery 1.9 is not working

I have this script:

jQuery(document).ready(function(){  
  $(".imgSwap").mouseenter(function() {
    $(this).src("_off").replaceWith("_on");
  }).mouseleave(function() {
     $(this).src("_on").replaceWith("_off");
  });
});

And this html:

<div id="nav">
  <table>
    <tr>
      <td class="tdleft">
      <img src="../../nav/prev_off.png" width="104" height="37" /></td>
      <td class="tdcenter">
        <img src="../../nav/crumb_on.png" width="30" height="30" alt="Pagina 1" />
         <img src="../../nav/crumb_off.png" width="30" height="30" />
      <img src="../../nav/crumb_off.png" width="30" height="30" /></td>
      <td class="tdright">
      <a href="p02.html"><img class="imgSwap" src="../../nav/next_off.png" width="104" height="37" /></a></td>
    </tr>
  </table>
</div>

I can not convince my image with class imgSwap to swap on mouseenter or mouseleave. I think the problem is in the replaceWith-part of the code. But I don't know how to fix it, and I couldn't find a clear example (clear to me, at least) on Stack Overflow either.

Upvotes: 1

Views: 171

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Instead of

$(this).src("_off").replaceWith("_on");

use

this.src =  this.src.replace("_off", "_on");

You want to do a replacement in the src string while replaceWith do DOM elements replacements.

You should also probably simplify your code using hover :

$(function(){  
    $(".imgSwap").hover(function() {
        this.src =  this.src.replace("_off", "_on");
    }, function(){
        this.src =  this.src.replace("_on", "_off");
    });
});

Upvotes: 2

Related Questions