soupagain
soupagain

Reputation: 1133

Remove onmouseover event from DOM elements efficiently

I have an HTML page that contains many onmouseover events. These events are linked to a,img,td and div tags.

What is the most efficient Javascript way to remove all the onmouseover events, presuming the page has loaded.

I'm not using jQuery.

(the task is to remove unneeded tooltips when the page is accessed using touch devices)

Upvotes: 4

Views: 15979

Answers (3)

Paul Nelson
Paul Nelson

Reputation: 147

A simple function looping through all the elements should do the trick. This one does it for all divs:-

function removeMouseOver() {
    var divs = document.body.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
        divs[i].onmoseover = function() {};
    }
}

another way is to define the mouseover tooltip function as a var

var tooltip = function(){// put your tooltip code here };
var donothing = function(){};

//to turn tooltips on:-
onmouseoverfunc = tooltip;

//to turn tooltips off:-
onmouseoverfunc = donothing;

in the elements

document.getElementById('mydiv').onmouseover = function(){mouseoverfunc();};

Upvotes: 2

y0ruba
y0ruba

Reputation: 234

Just add a unique class to everything that has the mouseover event and then make a loop

get=document.getElementsByClassName("classhere");
for(i=0; i<get.length; i++){
    get[i].removeEventListener("mouseover", yourFunction, false);
   }

replace yourFunction and classhere, tell me if it works or not

Upvotes: 1

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

Since all your event handlers point to the same central function - you can disable tooltips inside of that function.

If this function handles both onmouseover and onclick events - you can check event.type and disable tooltips only if it's equal mouseover.

Demo: http://jsfiddle.net/cLHgK/1/

Upvotes: 1

Related Questions