jQuery combining focus and hover

12,884

Solution 1

Focus is for <input/> elements and <a/> links...

Solution 2

You can also bind both events at once:

$('#main-menu ul.rubriques li').bind('hover focus', function() {
    $(this).addClass('active').find('ul').show();                    
});

But like michelgotta says the focus is unlikely to work on an li except in some circumstances - http://api.jquery.com/focus/

Solution 3

Only inputs, textareas and anchors can get focus.

Also, you're missing a ) after the hover() part

$('#main-menu ul.rubriques li').hover(function() {
    $(this).addClass('active').find('ul').show();                    
}).focus(function() {
    $(this).addClass('active').find('ul').show();                    
});

Update - as pointed out by @vittore, li's can get focus if you assign a tab-index

Solution 4

Focus is a function that you use only on form elements like input field for example, if I remember rightly.

http://api.jquery.com/focus/

What are you trying to do?

If you waht to do something with the li element use;

$('#main-menu ul.rubriques li').hover(function() {
  $(this).addClass('active').find('ul').show().css({'border':'1px solid #ff2200','background-color':'#ffcc00'});
});

You can change the colors to whatever you want. That's your best alternative.

Share:
12,884
halna frédéric
Author by

halna frédéric

By Day: Digital Accessibility Consultant By Night: Tanaguru Master: tanaguru For fun: Iceland lover

Updated on August 04, 2022

Comments

  • halna frédéric
    halna frédéric over 1 year

    I am trying to use focus event on list element. it's working with hover, but not with focus! Do you have a idea ?

    $('#main-menu ul.rubriques li')
    .hover(function() {
    $(this).addClass('active').find('ul').show();                    
    })
    .focus(function() {
    $(this).addClass('active').find('ul').show();                    
    });
    

    i try to modify my code: and find the solution ;) ;) ;)

      $('#main-menu ul.rubriques li a')
    .hover(function() { $(this).parent().addClass('active').find('ul').show();                   
    })
    .focus(function() { $(this).parent().addClass('active').find('ul').show();                   
    });
    

    thanks ! everybody !