1

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>

2 Answers 2

1
['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);
    });
} );
Sign up to request clarification or add additional context in comments.

Comments

0

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');
  });

1 Comment

Is this slightly more performant than what I had? I assumed combining them would be beneficial somehow.

Your Answer

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.