Reputation: 7
I altered the following code and replaced .hover with .click. Everything is working fine except the lack of an "offclick" function. With .hover it was no issue. How do I add to this to account for clicking off the element. ul visibility should be 'hidden' when clicking off, outside, etc.
$(document).ready(function(){
if($("ul.dropdown").length) {
$("ul.dropdown li").dropdown();
}
});
$.fn.dropdown = function() {
return this.each(function() {
$(this).click(function(){
$(this).addClass("click");
$('> .dir',this).addClass("open");
$('ul:first',this).css('visibility', 'visible');
},function(){
$(this).removeClass("click");
$('.open',this).removeClass("open");
$('ul:first',this).css('visibility', 'hidden');
});
});
}
Upvotes: 0
Views: 2439
Reputation: 146191
The hover
event has actually two states, in other words, for the hover
event there are two different events are used behind the scene and these are mouseenter
and mouseleave
so when you hover over an element the mouseenter
event gets fired and on hovering off the element the mouseleave
event gets fired, so in this case, you can't convert this event to click
using two methods like hover
instead, you just declare one click
event handler (function) for that element. For example, you may do something like this:
$('#element').on('click', function(e){
//...
});
If you want to change the state of the element when another element gets clicked then you should catch the click event for that element so clicking on tnother element you may do the opposite thing. For example, you may register a click event on $('body')
so when click happens on the body
then you may do the opposite thing.
Upvotes: 0
Reputation: 8072
This is the way how can you check that user clicked outside
$(document).click(function () {
//hide ul there
});
$(this).click(function(event){
event.stopPropagation(); // this forbid parent clicks (on document)
$(this).addClass("click");
$('> .dir',this).addClass("open");
$('ul:first',this).css('visibility', 'visible');
});
Upvotes: 0
Reputation: 4635
You can use jQuery's .toggle()
for this.
$(SELECTOR).toggle(function () {
// State 1
}, function () {
// State 2
});
Upvotes: 1