views:

108

answers:

2

How to enable hover only on one particular DIV for IE 6 through javascript. I want to enabe hove on one div only I found some script on net to make this possible but they applied on whole site i think rendering time will be increased so i want to enable hover only on one particular div.

IE7. js can do this but is has some more unwanted things which i dont' want so i need simple short javascript code to enable hover in IE 6

+1  A: 
var elem = document.getElementById('divid');
elem.onmouseover = function(e) {
  if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  // do operation using e
};

elem.onmouseout = function(e) {
// get e using code from above
};

This will allow you to put in code for a particular element, just change the css or do whatever else you want.

To get an idea as to which events work on which browser you can use this: http://www.quirksmode.org/dom/events/index.html

James Black
can we use css class like document.getElementByclass
metal-gear-solid
@Jitendra - Not with IE6. http://stackoverflow.com/questions/900117/is-getelementbyclass-safe-to-use-across-browsers-like-getelementbyid
James Black
+1  A: 

A simple onmouseover/onmouseout has the downside that it will be also fired when the div has childnodes and you hover this child. So you will get an mouseout fired when you hover the childnode. Every framework has something like mousenter/mouseleave to handle this problem. So in JQuery it should look like this:

$('#myElement').mouseenter(toggleClass(true)).mouseleave(toggleClass());
function toggleClass(enter){
  if(enter){
     /*do something on mouseenter*/
  }else {
     /*do something on mouseleave*/
  }

/or the much shorter version/ $('#myElement')(enter ? 'add' : 'remove') + 'Class'; }

eskimoblood
If this is only for IE then mouseenter/mouseleave is a good choice. I tend not to think about them as I focus on cross-browser development.
James Black