Showing sublist items fades in on hover()
, but not click()
or onclick()
.
http://jsfiddle.net/gymbry/mgMK4/
Asked
Active
Viewed 88 times
-5

gymbry
- 25
- 4
-
1jQuery object doesn't have `onclick` method. – Ram Dec 02 '13 at 19:11
-
[Full answer with `commented` explinations](http://stackoverflow.com/questions/20335942/fadein-working-on-hover-but-not-onclick-click#answer-20336016) – SpYk3HH Dec 02 '13 at 19:36
1 Answers
2
Simplest solution:
$('ul li').click(function (e) { // jQuery click event. The "e" is the "event" argument
e.stopPropagation(); // prevents a parent elements "click" event from fireing (useul here since this asigns to inner li's as well)
var ul = $(this).children('ul'); // find any children "ul" in this li
// check if ul exist and toggle (not completely neccesary as jquery will simply preform no action if element is not found)
if (ul.length) ul.fadeToggle('fast');
});
$('ul li').click(function (e) { // jQuery click event. The "e" is the "event" argument
e.stopPropagation(); // prevents a parent elements "click" event from fireing (useul here since this asigns to inner li's as well)
var ul = $(this).children('ul'); // find any children "ul" in this li
if (ul.length) { // check if ul exist
if (ul.is(':visible')) { // check ul is visible
ul.fadeOut('fast');
}
else {
ul.fadeIn('fast');
}
}
});
Keep in mind, the above solution doesn't deal with siblings or deeper menus being open upon close. For a more full solution, try the following:
$('ul li').click(function (e) {
e.stopPropagation();
var ul = $(this).children('ul');
$(this).siblings().each(function(i) {
var ul = $(this).children('ul');
if (ul.length) if (ul.is(':visible')) {
ul.find('ul').fadeOut('fast');
ul.fadeOut('fast');
}
});
if (ul.length) {
if (ul.is(':visible')) {
ul.find('ul').fadeOut('fast');
ul.fadeOut('fast');
}
else ul.fadeIn('fast');
}
});

SpYk3HH
- 22,272
- 11
- 70
- 81
-
1
-
@BramVanroy I wasn't finished editing answer. And the OP doesn't seem to have a strong grasp of what is going on, thus the break down of more elaborate solutions. Also, a simple solution will not account for a lot of possible "problems" that will arise, such as dealing with sibling menus – SpYk3HH Dec 02 '13 at 19:32
-