skip to Main Content

I am using jQuery to handle something. It relates to many class or id having a prefix ‘receive’ in its name. Now I want to duplicate those function, but with the prefix ‘send’. It looks like this

function onSelectAddress() {
    $('#receive-address').on('click', function() {
        $('#receive-dropdown').show();
        $('#receive-address').addClass('box-click');
    });
    $('#send-address').on('click', function() {
        $('#send-dropdown').show();
        $('#send-address').addClass('box-click');
    });
}

I don’t want to copy paste and change ‘receive’ to ‘send’ line by line. Is there any way to handle this problem?

3

Answers


  1. One way I can think of to optimize your code is to create a generic function that takes a receive and send as a parameter and handles both cases. Something like(code is untested but you get the idea):

    function generic(prefix) {
        $(`#${prefix}-address`).on('click', function() {
            $(`#${prefix}-dropdown`).show();
            $(`#${prefix}-address`).addClass('box-click');
        });
    }
    // To use
    function setupAddressHandlers() {
        generic('receive');
        generic('send');
    }
    // ...rest of code
    
    Login or Signup to reply.
  2. Refactor by creating a generic function which accepts a prefix:

    function doTheThing(prefix) {
        $(`#${prefix}-address`).on('click', function() {
            $(`#${prefix}-dropdown`).show();
            $(`#${prefix}-address`).addClass('box-click');
        });
    }
    

    Note the use of backticks for string interpolation.

    Then use it:

    function onSelectAddress() {
      doTheThing('receive');
      doTheThing('send');
    }
    
    Login or Signup to reply.
  3. function onAddressClick() {
      $('.address').on('click', function() {
        var action = $(this).data('action');
        $('#' + action + '-dropdown').show();
        $(this).addClass('box-click');
      });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="receive-address" class="address" data-action="receive">Receive Address</div>
    <div id="send-address" class="address" data-action="send">Send Address</div>
    
    <div id="receive-dropdown" class="dropdown">Receive Dropdown</div>
    <div id="send-dropdown" class="dropdown">Send Dropdown</div>

    This code uses a common class "address" for both ‘receive-address’ and ‘send-address’ elements and utilizes the data-action attribute to determine whether it’s a ‘receive’ or ‘send’ action. This way, you avoid duplicating the code and make it more maintainable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search