Probably, what you want is to toggle 'active' class whenever 'clickme' link is clicked. Also, if 'active' class is already added, you want to remove that when clicked anywhere on the document.
For this,
1) Why your code doesn't work:
You are using two events, mouseup and click: mouseup is always triggered just before click whenever same element is binded with both of these events. In your case same is happening.
When you click on 'myLink', you actually also trigger mouseup of document. This mouseup event removes 'active' class and click event adds 'active' class. That is why, whenever you click on 'myLink', active class is always added and you always see yellow color background.
2) Solution: Try using click instead of mouseup for document event binding and event.stopPropagation in click handler of 'myLink'.
fiddle: https://jsfiddle.net/tgowvehx/5/
code:
$('.mylink1').click(function(evt){
evt.stopPropagation();
if ($('.div1').hasClass('active')){
$('.div1').removeClass('active');
} else {
$('.div1').addClass('active');
}
});
$(document).click(function (e)
{
var container = $(".div1");
if (!container.is(e.target)
&& container.has(e.target).length === 0)
{
$('.div1').removeClass('active');
}
});
$('.div1').toggleClass('active');Updated fiddle jsfiddle.net/tgowvehx/2.activeand when the second function is executed it ads the class back to it.mouseuphandler is removing it just before theclickhandler runs. Here's one way to fix that: jsfiddle.net/tgowvehx/3