Search code examples
javascriptjquerycssshow-hidemousehover

show div on click and hide if hover on another


I want to show div on hover. Its working fine. Now what actually I want is to add a class if any user click on anchor tag then display div and not hide if mouse leaves on it. Class will get removed if user clicks on anchor tag again or hovered on another div.


    $('#main-menu a').mouseover(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.show().siblings('.widget-container').hide();
    });
    $('#wrap').mouseleave(function() {
        $('.widget-container').hide();
    });
    $('#main-menu a').click(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.addClass('active').siblings('.widget-container').hide();
    });
    $('#wrap').mouseleave(function() {
        $('.widget-container').hide();
    });

Check it here: Fiddle


Solution

  • See this: Demo

    $('#main-menu a').mouseover(function() {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.show().siblings('.widget-container').removeClass('active').hide();
    });
    

    And for the anchor tag:

    $('#main-menu a').click(function(e) {
       var $this = $(this);
       var id = $this.attr('rel');
       var $currentWidget = $('#' + id);
       $currentWidget.toggleClass('active').siblings('.widget-container').removeClass('active').hide();
       e.preventDefault();
    });