"Delegates in Swift 2" was retired on May 31, 2020. You are now viewing the recommended replacement.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to change pictures jQuery [Solved]

Hi,

I want to change a picture within a div when mouse hovers over picture. I want it work with jQuery. (I know, it is much easier with CSS.)

My HTML looks like this:

<div class="col-sm-3">
    <b class="glyphicon glyphicon-tree-conifer"></b>
      <h2>
    Nadelbäume.
  </h2>
  <img src="img/Planten.jpg" id="Planten">
  <img src="img/rabe.jpg" id="rabe">

  </div> <!--class col ende-->

(Yes, I am working with the Bootstrap framework. :) )

The jQuery looks like this:

console.log("halo");

$("#rabe").hide();

$( "#Planten" ).hover(function() {
    $(this).show("#rabe" );
  }
);

(The console.log only serves the purpose to show me, whether the script is loaded.)

The img with the id "rabe" is hidden because when not, it is displayed under the img with the id "Planten".

Thanks in advance for your help.

Best and greetings from Germany,

Sven

5 Answers

$('img').on('mouseenter', function(){
    $(this).attr('src', 'img/rabe.jpg');
}).on('mouseleave', function(){
    $(this).attr('src', 'img/Planten.jpg');
});

You only need one img to make this work, then you swap the src value on hover (I use mouseenter/leave instead of hover,).

why dont you use the attr() function and change the src link of the image on hover?

For example:

$('#planten').hover(function() {
    $(this).attr('src', 'img/rabe.jpg');
}, function() {
    $(this).attr('src', 'img/Planten.jpg');
});

Many thanks Stanley. I've copy / pasted your solution. But it does not work. But I will check the attr() fuction, which also seems to be crucial in the other solutions. Best, Sven

Hi Sven,

It should be working fine. I think it doesnt work now because i used #planten selector instead of #Planten :)

So if you use $('#Planten') instead it should work fine!:D

damn i am some seconds too late :'(

http://codepen.io/anon/pen/OyQaXO

@Matthias @Jeff many thanks.

@Stanley: Yes, your are absolutely right. Copy-Paste mode occupied to much capacity. :)