Josh
Josh

Reputation: 615

Issues with this css/jquery combo

Show/hide works perfectly fine. I can click #business which opens my menu, click outside the element 'html' which closes the menu, or click #business again.

Problem 1: #business does not revert back to #323232.

Problem 2: If I click inside of the new menu (#businessmenu) jquery hides it, how can I only hide it by clicking outside of the element or on #business toggle?

JavaScript:

$("#business").click(function(event){
    jQuery.fx.off = true;
    $("#businessmenu").toggle("");
    $(this).css("background-color", "#000");
    event.stopPropagation();
});
$('html').click(function() {
    $("#businessmenu").hide();
    $("#business").css("background-color", "#323232");
});

CSS:

header {
  float: left;
  background: #323232;
  width: 98%;
  padding: 0 1%;
  color: #E9F1F4;
}

header a {
  color: #e9f1f4;
  font-size: 20px;
  font-weight: bold;
}
header a:hover {
  background: #000;
  color: #fff;
}

header #business {
  float: left;
  position: relative;
  padding: 10px 35px 13px 20px;
}

#businessmenu {
  display: none;
  background: #000;
  width: 220px;
  height: 200px;
  position: absolute;
  top: 60px;
  left: 1%;
  border-radius: 0 0 6px 6px;
  padding: 10px 35px 13px 20px;
}

HTML:

<a href="#" id="business">Name</a>

<div id="businessmenu">             
    <a href="help.html">Help</a>                
</div>

Upvotes: 2

Views: 133

Answers (2)

I.G. Pascual
I.G. Pascual

Reputation: 5965

What you're looking for is stopImmediatePropagation and isImmediatePropagationStopped methods for your click events.

As there is more logic rather than just 'togglin', because if you click outside, you're not toggling #business, you're just hiding the #businessmenu, and forcing a toggle means adding even more logic.

Here is a jsfiddle with your full working example: http://jsfiddle.net/mG5vS/1

For your 1st problem, I just added an if statement inside the click event:

$("#business").click(function(e){
    if($("#businessmenu").is(":hidden")) {
        //...do things
        e.stopImmediatePropagation(); //don't hide menu right after showing
    } else {
        hide(); //hide/revert to everything to initial state
    }
});

For your 2nd problem, I added those stop event propagation functions like this:

$("#businessmenu").click(function(e){
     e.stopImmediatePropagation(); //don't hide when clicking menu links
});

$('html').click(function(e) {
    if(!e.isImmediatePropagationStopped()){ //Hide unless told not to
        hide();
    }
});

Upvotes: 1

Evgeny Lukashevich
Evgeny Lukashevich

Reputation: 1517

You can actually use toggle for toggling css classes when your element is clicked

$('#business').toggle(function() {
  $(this).addClass('toggled');
}, function() {
  $(this).removeClass('toggled');
});

Now with demo :) http://jsfiddle.net/8CJnV/

Upvotes: 2

Related Questions