nsilva nsilva - 10 months ago 65
jQuery Question

jQuery - Change image src on hover

Basically I want to change the image src to add

on hover.

So fb.png would become fb-active.png on hover, and fb.png when it's not hovering.

I'm not too sure what I am doing wrong so I'll post my code so far:-


<div id="main-contact" class="right">

<div id="main-social">

<a href="#!"><img class="img-social" alt="Company - Facebook" class="left" src="images/fb.png" /></a>

<a href="#!"><img class="img-social" alt="Company - Twitter" class="left" src="images/twitter.png" /></a>

<a href="#!"><img class="img-social" alt="Company - LinkedIn" class="left" src="images/linkedin.png" /></a>

<a href="#!"><img class="img-social" alt="Company - Word Press" class="left" src="images/wordpress.png" /></a>




$(document).ready(function() {

var regexactive = /-active\..*$/;

var ct = $('#main-social');
var imgs = $('.img-social img', ct);

function activateImage(imgs){
var img = $(this);
var src = img.attr('src');
if( !regexactive.test(src) ){
img.attr('src', src.replace('.png', '-active.png'))

ct.on('hover', '.img-social', function(){

var img = $('.img-social img');


Answer Source

This can be done without javascript, with only css. Like this:

Give different classes for icons like fb for facebook,tw or twitter and so on.


<div id="main-social">    
    <a href="#!"><span class="img-social fb left" title="Company - Facebook"></span></a>
    <a href="#!"><span class="img-social tw left" title="Company - Twitter"></span></a>
    <a href="#!"><span class="img-social ln left" title="Company - LinkedIn"></span></a> 
    <a href="#!"><span class="img-social wp left" title="Company - Word Press"></span></a> 



You can use sprite for efficiency.