3
\$\begingroup\$

I wrote a script to change a static image by hovering over navigation links. It works great, however, the script is very long and I'm guessing there is a much more efficient way to write this code. Can anyone give me tips on a better way to do this?

HTML

<ul id="navigation">
  <li><a id="1" href="#">Link 1</a></li>
  <li><a id="2" href="#">Link 2</a></li>
  <li><a id="3" href="#">Link 3</a></li>
</ul>
<div class="box">
  <img src="default.jpg"/>                    
</div>

JQuery

$(document).ready(function() {
$('#navigation li a#1').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image1.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
$('#navigation li a#2').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image2.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
$('#navigation li a#3').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', 'image3.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
});
\$\endgroup\$
1

2 Answers 2

1
\$\begingroup\$

Add a new attribute to your divs, in this case we will use data-filename. You could even use the index of each element in the list, but if you want to use custom names in your images is better the use a new attribute.

<ul id="navigation">
  <li><a id="1" href="#" data-filename="image1">Link 1</a></li>
  <li><a id="2" href="#" data-filename="image2">Link 2</a></li>
  <li><a id="3" href="#" data-filename="image3">Link 3</a></li>
</ul>
<div class="box">
  <img src="default.jpg"/>                    
</div>

Simplify your script

$(document).ready(function() {
$('#navigation li a').hover(
    function(){
        //we get our current filename and use it for the src
        var linkIndex = $(this).attr("data-filename");
        $(this).addClass('hover');
        $('.box img').attr('src', linkIndex+'.jpg');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
});
\$\endgroup\$
0
1
\$\begingroup\$

Refactor the function from the data. Then you can just bind the same function to all of the links.

html

  <li><a id="1" href="#" data-img='image1.jpg'>Link 1</a></li>

js

$('#navigation li a').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', $(this).data('img');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.