Chris S-E
Chris S-E

Reputation: 21

Combine Two identical jQuery functions except they use different selectors and classes

I have two functions that do the same thing, except the element I am targeting is different and so is the ID I want to add. What is the best way to combine these into a single function?

  <script>
      $('.Index-page--has-image[id*="angle-right"]').each(function(){
        var index = $(this).index('.Index-page--has-image')
        $('.Parallax-host .Parallax-item').eq(index).attr('id','angle-right');
      });
        $('.Index-page--has-image[id*="angle-left"]').each(function(){
        var index = $(this).index('.Index-page--has-image')
        $('.Parallax-host .Parallax-item').eq(index).attr('id','angle-left');
      });
    </script>

Upvotes: 1

Views: 31

Answers (2)

r043v
r043v

Reputation: 1869

['left','right'].forEach( way => {
    way = 'angle-' + way ;
    $('.Index-page--has-image[id*="'+way+'"]').each(function(){
        var index = $(this).index('.Index-page--has-image');
        $('.Parallax-host .Parallax-item').eq(index).attr('id',way);
    });
} );

Upvotes: 1

Ben.S
Ben.S

Reputation: 746

Extract the function outside the JQ each function, and pass the angle value to the function parameter, like this

function yourFunctionName(element, idValue){
  let index = $(element).index('.Index-page--has-image')
  $('.Parallax-host .Parallax-item').eq(index).attr('id', idValue);
}
 $('.Index-page--has-image[id*="angle-right"]').each(function(){
     yourFunctionName(this, 'angle-right');
  });
  $('.Index-page--has-image[id*="angle-left"]').each(function(){
     yourFunctionName(this, 'angle-left');
  });

Upvotes: 0

Related Questions