Search code examples
javascriptjquerydryjquery-wrap

How to wrap multiple dynamic eventListeners into one?


I just started to learn js and need a little help: I have the following function:

   //SET CHAT BEHAVIOR
   function chatSettings() {

        console.log('ChatSettings called')         

        function BtnAndScrollBar(texteditor) {     
            console.log('BTNAndScrollBar called');    
            const sendBtn = $('.cl.active').find('.sendBtn');
            const attachBtn = $('.cl.active').find('.attachBtn');
            console.log(sendBtn)          
        }

        function sendAndDeleteMessage(send) {
            console.log(send);
        }   

        var sendBtn = $('.cl.active').find('.sendBtn');
        sendBtn.mousedown(function () {      
            sendAndDeleteMessage(this);
        });               

        var textEditor1 = $('.cl.active').find('.chatTextarea');                  
        textEditor1.on('focus change mousedown mouseout keyup mouseup', function (){
            console.log(this);
            BtnAndScrollBar(this)
        });
   }       

      $('document').ready(function () {
          console.log('hello');
          $('.tabs').tabs();
          chatSettings();        
      });

I prepared a js.fiddle - As you can see from console.log when clicking into the textarea, the eventListener always listens to #cl1, even if .cl.active switches along with the according TAB.

The events in the textarea are just relevant, if .cl is active. My target is to wrap all three eventListener into one and apply the event to the textarea in the active stream, but all I tried went wrong... Can anyone help? #Dontrepeatyourself #DRY


Solution

  • $(".chatTextarea").on(
    'focus change mousedown mouseout keyup mouseup', 
    function (this) {
    //this.id can contain the unique id
    greatFunction(this);
    }); 
    

    This will bind event individually with unique id found with this keyword and also wraps all event listener into one function but this is better when you want to process each event with same functionality

    please let me know if this helps.

    Peace