javascriptjquery

JQuery Tidy Up Code


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?


Solution

  • 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.