views:

63

answers:

2

What would be jQuery equivalent of this sf hover suckerfish code?

<script>
sfHover = function() {
   var sfEls = document.getElementById("navbar").getElementsByTagName("li");
   for (var i=0; i<sfEls.length; i++) {
      sfEls[i].onmouseover=function() {
         this.className+=" hover";
      }
      sfEls[i].onmouseout=function() {
         this.className=this.className.replace(new RegExp(" hover\\b"), "");
      }
   }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
</script>
+4  A: 
$(function(){         // equivalent to [.ready()][1] syntax (i.e. fire on load)
  $('#navbar li').hover(  // attach hover event to any li descendant of element with id=navbar
    function(){$(this).addClass('hover')},    // $(this) signifies the li element that was hovered over, so we add the 'hover' class to it
    function(){$(this).removeClass('hover')}  // then remove it onmouseout
  );
});

No conflict version:

$.noConflict();
jQuery(document).ready(function($) {
  $('#navbar li').hover(
      function(){$(this).addClass('hover')},
      function(){$(this).removeClass('hover')}
    );
});
// Code that uses other library's $ can follow here.
John Rasch
pls give me noconflict version also
metal-gear-solid
+1 - great answer John.
Scott Ivey
@John Rasch - just checked no conflict version not working
metal-gear-solid
@metal-gear-solid how's about saying "Thanks for that, your answer will really help me earn some bucks - but I'm not sure your second example works because x y z." Show a little appreciation for all the work people put in.
adam
@adam - Thanks. your wording is really good. Will follow this in future.
metal-gear-solid
+1  A: 

Along with @john Rashh's answer, you could also handle the mouseover and mouseout functions separately...

$(document).ready(function() {

   $("#navbar li").mouseover(function() {
      $(this).addClass("hover");
   });

   $("#navbar li").mouseout(function() {
      $(this).removeClass("hover");
   });

});
Scott Ivey
what is the benefit to handle separately?
metal-gear-solid
No benefit that I know of - maybe more explicit code at best? I think I like the hover event over doing the mouseover and mouseout events separately.
Scott Ivey