I'm working with the next html structure:
<ul class="menu">
<li class="item">
<small>Ubicacion</small>
<a class="item-content" href="#">
<i class="item-icon fas fa-map-marker-alt"></i><span>Ubicaciones</span>
<i class="down fas fa-sort-down"></i>
</a>
<ul class="sub-menu ubicaciones">
<li class="sub-item">Ubicacion1</li>
</ul>
</li>
</ul>
This code is a part of the next sidebar
I have this Jquery code:
$('.menu .item').click(function () {
$(this).find('.item-content .down').toggleClass('active')
$(this).find('.sub-menu').toggleClass('active')
})
With this code I just get the element with the class down that is the arrow icon and I add the class active to rotate arrow up. and I make the same with the element with the class sub-menu I add class active to show it
Also I have this code:
$(document).on('click', '.sub-item', function (evemt) {
event.preventDefault()
console.log('Hola!')
})
With this code I want to get the text inside sub-item element but when I make click in any alement with the class sub-item the class active is remove from my elements down and sub-menu and sub-menu is hidde and I don't want this I tried using preventDefault but it don't work
Can someone tell me what is my error?
You can do that with the help of single event handler, like this :
$('.menu .item').click(function(event) { if ($(event.target).hasClass('sub-item')) { console.log('Hola!') } else { $(this).find('.item-content .down').toggleClass('active') $(this).find('.sub-menu').toggleClass('active') } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="menu"> <li class="item"> <small>Ubicacion</small> <a class="item-content" href="#"> <i class="item-icon fas fa-map-marker-alt"></i><span>Ubicaciones</span> <i class="down fas fa-sort-down"></i> </a> <ul class="sub-menu ubicaciones"> <li class="sub-item">Ubicacion1</li> </ul> </li> </ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.