Search code examples
javascriptonclickonmouseoveronhover

Combine onlick and onmouseover in the same function


I want to combine onclick and onmouseover in the same line.

I have

if (var) {
        var.onclick = function() {
//          do something
}

I want to add

if (var) {
            var.onclick || var.onmouseover= function() {
    //          do something
    }

Something like that


Solution

  • All the events can be stored in an array which can be iterate & use addEventListener to add attache the event with the element

    var x = document.getElementById("test")
    
    if (x) {
      ['click', 'mouseover'].forEach(function(item) {
        x.addEventListener(item, function(event) {
          console.log(event.type)
        })
      })
    }
    <button id="test">Test Button</button>