-1

Am using a bit of javascript to animate an a class within a div class.

$(".previouscontainer").mouseenter(function(){
    $("a.previousarrow").animate({left:'0px'},"fast");
  });
$(".previouscontainer").mouseleave(function(){
    $("a.previousarrow").animate({left:'10px'},"fast");
  });
$(".nextcontainer").mouseenter(function(){
    $("a.nextarrow").animate({right:'0px'},"fast");
  });
$(".nextcontainer").mouseleave(function(){
    $("a.nextarrow").animate({right:'10px'},"fast");
  });

Was wondering whether there is a better/cleaner way to write this?

4
  • You should include the related HTML. Commented Jan 11, 2013 at 7:52
  • There is no need for the HTML for this question Commented Jan 11, 2013 at 7:57
  • Just thought that a.nextarrow might be a child element of .nextcontainer and that $(this).find("a.nextarrow") could be useful... never mind. Commented Jan 11, 2013 at 8:04
  • @Stefan yes that's a good point. $(this).find("a.nextarrow") is not much quicker than $("a.nextarrow") but if it was a case of $(this).find('a') that would be tidier at least Commented Jan 11, 2013 at 8:05

1 Answer 1

1

You can chain them.

$(".previouscontainer").mouseenter(function(){
    $("a.previousarrow").animate({left:'0px'},"fast");
  }).mouseleave(function(){
    $("a.previousarrow").animate({left:'10px'},"fast");
  });
$(".nextcontainer").mouseenter(function(){
    $("a.nextarrow").animate({right:'0px'},"fast");
  }).mouseleave(function(){
    $("a.nextarrow").animate({right:'10px'},"fast");
  });

or use hover which takes both functions

$(".previouscontainer").hover(function(){
    $("a.previousarrow").animate({left:'0px'},"fast");
  },function(){
    $("a.previousarrow").animate({left:'10px'},"fast");
  });
$(".nextcontainer").hover(function(){
    $("a.nextarrow").animate({right:'0px'},"fast");
  },function(){
    $("a.nextarrow").animate({right:'10px'},"fast");
  });

Or you can go mad and create your own event

$("a.previousarrow").on('moveme', function(){
    if ($(this).css('left')>0) $(this).animate({left:'0px'},"fast");
    else $(this).animate({left:'10px'},"fast");
});

if you need to bind it to various actions that can't be in the same selector

$(".previouscontainer").on('mouseover mouseleave', function(){ 
    $("a.previousarrow").trigger('moveme');
});

$('#somethingelse').on('click', function(){
    $("a.previousarrow").trigger('moveme');
});

There are other ways to swing this cat. .hover() is the most sensible.

Sign up to request clarification or add additional context in comments.

2 Comments

May I suggest an improvement to this answer: Consider "caching" the selectors to reduce load.
i'm not sure it would help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.