skip to Main Content

I’m new to JavaScript,this question may looks very silly.

I have function like this:

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('mySelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

And another almost same function like this:

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('newSelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

The only difference is the id ,my question is how to add the 2 ids into this same function ?

maybe something like this:

for id in ['mySelectOptions','newSelectOptions']:
      document.addEventListener('mouseup', function(e) {
    var container = document.getElementById(id);
    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
});

3

Answers


  1. You can do that with .querySelectorAll to select all match elements with different id. These id can be write with , splitter (#newSelectOptions,#mySelectOptions).

    document.addEventListener('mouseup', function(e) {
        var containers = document.querySelectorAll('#newSelectOptions,#mySelectOptions');
        [...containers].forEach(function(container) {
            if (!container.contains(e.target)) {
                container.style.display = 'none';
            }
        });
    });
    
    Login or Signup to reply.
  2. You can create a function that wrap your DOM function code

    function hideContainer(containerId) {
        var container = document.getElementById(containerId);
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    }
    
    document.addEventListener('mouseup', function(e) {
        hideContainer('mySelectOptions');
    });
    
    
    document.addEventListener('mouseup', function(e) {
        hideContainer('newSelectOptions');
    });
    
    Login or Signup to reply.
  3. You can create an array of the Ids in case you do not want to work with classes.

    let elemntsIds= ['mySelectOptions', 'newSelectOptions'];
    
    elemntsIds.forEach(function(id) {
      document.addEventListener('mouseup', function(e) {
        var container = document.getElementById(id);
        if (!container.contains(e.target)) {
          container.style.display = 'none';
        }
      });
    });
    

    Keep in mind that I used the let for defining the array outside the function handler body since it is block-scoped, you will need to declare it as var inside the function handler body so it can be hoisted and to avoid a new instance from being created each time the event is triggered

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