'jQuery click + if + .find function not working
Going nuts here.
Trying to write a function where if there's a '.child' class element inside the container, the function fires, but otherwise does nothing.
However, using .find() (as it's not a direct child) doesn't seem to do anything.
$(function() {
$('.menu-box li').click(function() {
if ($('.menu-box li').find('.child')) {
showContent($(this));
function showContent(elem) { // Add open classes when sub menu clicked
hideContent();
elem.find('.content').addClass('expanded');
elem.addClass('cover');
}
function hideContent() { // Remove open classes when sub menu closed
$('.menu-box .content').removeClass('expanded');
$('.menu-box li').removeClass('cover');
}
$('.menu-box .sub-menu').append('<span class="close left-arrow"></span>'); // Add close button to sub menu
$('.menu-box .close').click(function(e) {
e.stopPropagation();
hideContent();
}); // Close sub menu on click
} else {
//do nothing
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="mega-menu inner_container">
<div class="menu-box">
<!-- item without any children -->
<li>
<span class="parent title">Parent title</span>
<div class="content">
<div class="inner_container sub-menu">
<span class="parent title">Parent title</span>
<ul class="two-col"></ul>
</div>
</div>
</li>
</div>
<div class="menu-box">
<!-- item with children -->
<li>
<span class="parent title">Parent title</span>
<div class="content">
<div class="inner_container sub-menu">
<span class="parent title">Parent title</span>
<ul class="two-col">
<li><span class="child title">Child title</span></li>
<li><span class="child title">Child title</span></li>
</ul>
</div>
</div>
</li>
<li><span class="child title">Child title</span></li>
<li><span class="child title">Child title</span></li>
<li><span class="child title">Child title</span></li>
<li><span class="child title">Child title</span></li>
</div>
</ul>
Any thoughts greatly appreciated. Been tweaking it for about 5 hours and just can't get it to work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|