1

I'm working with some very basic jquery code and would like to condense what I've done into one function with passed parameters.

I have a few of these:

$(".about").hover(function() {
 $(this).attr("src","_img/nav/about_over.gif");
 }, function() {
 $(this).attr("src","_img/nav/about_off.gif");
});
$(".artists").hover(function() {
 $(this).attr("src","_img/nav/artists_over.gif");
 }, function() {
 $(this).attr("src","_img/nav/artists_on.gif");
});
$(".help").hover(function() {
 $(this).attr("src","_img/nav/help_over.gif");
 }, function() {
 $(this).attr("src","_img/nav/help_off.gif");
});

But would obviously like to pass the the title of the image ("about", artists", "help") so that I could cut down on repeated code.

Any help much appreciated.

Thanks

Ronnie

asked Jul 29, 2009 at 19:37
0

4 Answers 4

4
function hover(img) {
 $("."+img).hover(function() {
 $(this).attr("src","_img/nav/"+img+"_over.gif");
 }, function() {
 $(this).attr("src","_img/nav/"+img+"_off.gif");
 });
}
answered Jul 29, 2009 at 19:41
Sign up to request clarification or add additional context in comments.

2 Comments

Need to change $(class_name) to $("." + class_name)
This is just changing the src attribute twice... so effectively rendering the first statement useless. You need to use a call back function for the _off.gif. See my answer.
1

You could something like this:

function ElementHover(class_name, src_over, src_off) {
 $("."+class_name+"").hover(function() {
 $(this).attr("src", src_over);
 }, function() {
 $(this).attr("src", src_off);
 });
}
answered Jul 29, 2009 at 19:46

Comments

1
function HoverPic(name){
 $("."+name).hover(function() {
 $(this).attr("src","_img/nav/"+name+"_over.gif");
 }, function() {
 $(this).attr("src","_img/nav/"+name+"_off.gif");
 });
}
answered Jul 29, 2009 at 19:47

Comments

0

I'm not sure what's going on with the second function in the hover function, but you can do something like this:

$(".about .artists .help").hover(function(){
 $(this).attr('src','_img/nav/' + $(this).attr('class') + '_over.gif')
});

you can apply the same principle to your on/off gifs too.

Harry
90.1k26 gold badges216 silver badges224 bronze badges
answered Jul 29, 2009 at 19:46

2 Comments

I used this one, but I fixed it by changing $(".about .artists .help") to $(".about, .artists, .help") Thanks for your help, everyone.
Then select this as your answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.