How to bind an event on two html elements

I have created a dropdown menu. This menu opens by pointing on a parent div. I want to hide this div when user leaves both, the parent div or dropdown menu

$(function(){
$('.a').live('mouseenter',function(){
    $('#dropdown').stop(false, true).hide();

    var id = $(this).attr('id');
    $('#dropdown').css({
        position:'absolute',
        top: $(this).offset().top + $(this).height() + 'px',
        right: '115px',
        left: $(this).offset().left + 'px',
        zIndex:1000,
        width:'100px'
    });

    $('#dropdown').stop().slideDown(500);

    if($('#dropdown').mouseleave() && $('#'+id).mouseleave()){
        $('#dropdown').slideUp(500);
    }
 });
});

Live Demo

Answers


you have to add mouseleave event and check the dropdown, to keep it short, try this

i hope this is what you wanted


You can bind to multiple elements by seperating them with commas in the selector

$('.a, .this, .that, div, form').live(....

Use multiple selector as @Dale suggested or use same class for both the elements and use

$(".commonClass").live(function(){

});  

If you want to bind same event to more elements you just need to apply commonClass to them instead of adding new selector.


Try this demo: http://jsfiddle.net/AQweU/ or http://jsfiddle.net/k986c/

Few things;

  • use .on event instead of live.
  • use this.id instead of $(this).attr('id').
  • not sure about this condition if($('#dropdown').mouseleave() && $('#'+id).mouseleave()){ see the code below what I have done

please note the demo in the question has Jq 1.7.2 hence the .on use.

rest checkout the code: (hope it help the casue) :)

$(function(){
    $('.a,#dropdown').on('mouseenter',function(){
        $('#dropdown').stop(false, true).hide();

        var id = this.id;
        $('#dropdown').css({
            position:'absolute',
            top: $(this).offset().top + $(this).height() + 'px',
            right: '115px',
            left: $(this).offset().left + 'px',
            zIndex:1000,
            width:'100px'
        });

        $('#dropdown').stop().slideDown(500);

        $('#dropdown, #'+id).mouseleave(function(){   
            $('#dropdown').slideUp(500);

        });
    });
});
​

Need Your Help

Creating war file

java linux ant war

I have extracted existing WAR file contents and modified few images. Now I have to re-create it to WAR file again using the extracted code from original war file.