Search code examples
functionvarlightsimplify

simplify functions jquery


I have these "functions" that are repeated in the block for the various elements. How can I simplify using "var"?

thank you : )

For example:

$('#test1').waypoint(function (direction) {
  if (direction === 'down') {
    $(this).addClass("here");
    $(this).prevAll().removeClass("here");
    $(this).prev().prev().addClass("here_pre");
    $(this).next().next().addClass("here_pre");
  },
});

I would like to arrive at a solution such as this:

var active_here = $(this).addClass("here"),
                  $(this).prevAll().removeClass("here"),
                  $(this).prev().prev().addClass("here_pre"),
                  $(this).next().next().addClass("here_pre");

And finally recall something like this:

$('#test1').waypoint(function (direction) {
  if (direction === 'down') {
  active_here;
  },
});

$('#test2').waypoint(function (direction) {
  if (direction === 'up') {
  active_here;
  },
});

etc... etc... etc...

Solution

  • Javascript variable function (or can be declared as normal function either):

    var active_here = function($elem){
        $elem.addClass("here");
        $elem.prevAll().removeClass("here");
        $elem.prev().prev().addClass("here_pre");
        $elem.next().next().addClass("here_pre");
    }
    

    Calling:

    $('#test1').waypoint(function (direction) {
      if (direction === 'down') {
        active_here($(this));
      },
    });
    
    $('#test2').waypoint(function (direction) {
      if (direction === 'up') {
        active_here($(this));
      },
    });