Adding multiple event listeners to a single function

There are times that having multiple event listeners tied to a single function will dramatically increase the usability of your website. For example, on most search bars, the search can be initiated by either clicking a button (usually a magnifying glass icon) or simply by hitting the enter key. Below we are going to look at how to implement multiple listeners to one function.

We first set up our function to call

<script>
      function displayAlert() {
            alert("The displayAlert() function was called.")
      }
</script>

Next we simply add the first event listener (in this case a button click) and call the displayAlert() function

<script>
     function displayAlert() {
          alert("The displayAlert() function was called.")
     }

     var btnSearch = document.getElementById('btnSearch');
     btnSearch.addEventListener('click', function() { 
          displayAlert() 
     }, false);
</script>

Finally we want to add an event listener for the keyup event of the enter key. Note that the keycode for the enter key is 13.

<script>
     function displayAlert() {
          alert("The displayAlert() function was called.")
     }

     var btnSearch = document.getElementById('btnSearch');
     btnSearch.addEventListener('click', function() { 
          displayAlert() 
     }, false);

     var searchBox= document.getElementById('searchBox');
     searchBox.addEventListener('keyup', function (event) {
          if (event.keyCode === 13) {
               btnSearch.click(); 
          }
     }, false);
</script>

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *