Html – Set child element attr using an attribute of the parent using jquery

csshtmljquery

I've got the following html:

<ul id="clients-strip">
    <li>
    <a href="http://example.com/case-studies/" data-colour="/images/made/assets/images/article-images/client-colour.png">
        <img src="/images/made/assets/images/article-images/client-grayscale.png" alt="Client" width="59" height="35">  
    </a>
    </li>
    </ul>

and need to basically swap the img src with the parent 'a' elements "data-colour" attribute when the 'a' element is hovered over (i'd like to fade out the old att and fade in the new too)

My jquery is not going too well 🙁

$('ul#clients-strip li a').hover(function(){
        $(this.' img').attr('src', this.data-colour);
    });

Any ideas as to what i'm doing wrong? Also, is it even going to be possible to essentially fade out one image and fade in another in the way that i'm trying here?

Best Solution

you should do

$('ul#clients-strip li a').hover(function(){
    //get the child image and change the src
    $('img', this).attr('src', $(this).data('colour'));
});

If you wan't to return to the original src when leaving you could do

var cacheSrc;
$('ul#clients-strip li a').hover(function(){
    cacheSrc = $('img', this).attr('src');
    //get the child image and change the src
    $('img', this).attr('src', $(this).data('colour'));
},
function(){
    $('img', this).attr('src',cacheSrc);
});