Search code examples
javascriptjqueryeventshandlermouseenter

How to give multiple events and handlers in .on method?


I'm trying to move a submenu by using multiple handlers in on method. What I want is if I moved my mouse on the one of li elements, event string mouseenter detects, then executes function panelON and same ways go between mouseleave and function panelOFF.

So I wrote the codes various ways but all of them didn't work and each of those have its own specific errors.

  target = $('#home-menu-nav ul li');
  target.on('mouseenter mouseleave', {
    convert: $('#submenu-content'),
    panelON(event) || panelOFF(event)
  })

  function panelON(event) {
    if (event.type == 'mouseenter') {
      console.log('fx panelON detected')
    } else {
      return
    }
  }

This one prints an error Unexpected token ||. Seems like || marks cannot be used with insdie of handlers.

Next one I tried is just grouped event and handlers all of them like in this article. link

  target.on( {mouseenter: panelON(event)}, {mouseleave: panelOFF(event)} )

  function panelON(event) {
    console.log('fx panelON detected')
  }

  function panelOFF(event) {
    console.log('fx panelOFF detected')
  }

And this was started immediately no matter what I hovered target or not.

  target = $('#home-menu-nav ul li');
  target.on( {mouseenter: function() {
    console.log('fx panelON detected')
  }}, {mouseleave: function() {
    console.log('fx panelOFF detected')
  }} )

Last one. This one only prints mouseenter. mouseleave doesnt work. Is there any ways to give and matching between events and handlers in .on method?


Solution

  • @kekboi, welcome to StackOverflow!

    Your second try,

    target.on( {mouseenter: panelON(event)}, {mouseleave: panelOFF(event)} ) 
    

    was quite close. Given that () on a function invokes the given function immediately, which is not what you intended, and as @Taplar has suggested - on takes an object on(object) - I suggest you use the following version.

    target.on({ mouseenter: panelON, mouseleave: panelOFF });
    

    $(function() {
        var target = $('button.mybutton');
        
        target.on({ mouseenter: panelON, mouseleave: panelOFF });
    
        function panelON(event) {
            console.log('fx panelON detected')
        }
    
        function panelOFF(event) {
            console.log('fx panelOFF detected')
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="mybutton">Hover Me Now</button>