Could you help me with this code?
JavaScript
x
13
13
1
$(document).ready(function(){
2
/* Panel Slide */
3
var btn = document.getElementsByClassName("btnBorder");
4
var i;
5
6
for (i = 0; i < btn.length; i++) {
7
var panel = btn[i].nextSibling;
8
btn[i].addEventListener("click", function() {
9
$(".btnBorder").hide();
10
panel.show();
11
});
12
}
13
});
JavaScript
1
19
19
1
<div id="menu" class="sector-row">
2
<ul>
3
<li>
4
<div class="btnBorder flex">Logo <i class="ml-auto fa fa-angle-right"></i></div>
5
<ul class="slide-panel">
6
demo
7
</ul>
8
</li>
9
<li>
10
<div class="btnBorder flex">Navigazione <i class="ml-auto fa fa-angle-right"></i></div>
11
</li>
12
<li>
13
<div class="btnBorder flex">Widgets <i class="ml-auto fa fa-angle-right"></i></div>
14
</li>
15
<li>
16
<div class="btnBorder flex">Footer <i class="ml-auto fa fa-angle-right"></i></div>
17
</li>
18
</ul>
19
</div>
I would like to make a menu slide with multi level but the element “slide-panel” is not showing up…
Advertisement
Answer
I’m not a big fan of mixing pure javascript with jquery .. so the next code is in jquery .. Also I prefer to use add/remove/toggleClass
instead of hide/show()
JavaScript
1
8
1
$(document).ready(function(){
2
$('.btnBorder').on('click' , function(e){
3
var ul_selector = $(this).next('ul.slide-panel'); // OR $(this).closest('li').find('ul.slide-panel');
4
e.stopPropagation(); // it will prevent the parent click if you've one
5
$('ul.slide-panel').not(ul_selector).addClass('hide'); // if you need to hide other slide-panels
6
ul_selector.toggleClass('hide'); // toggle the class hide which in css is display:none and added to the slide-panel html element
7
});
8
});
JavaScript
1
3
1
.slide-panel.hide{
2
display : none;
3
}
JavaScript
1
20
20
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="menu" class="sector-row">
3
<ul>
4
<li>
5
<div class="btnBorder flex">Logo <i class="ml-auto fa fa-angle-right"></i></div>
6
<ul class="slide-panel hide">
7
Demo
8
</ul>
9
</li>
10
<li>
11
<div class="btnBorder flex">Navigazione <i class="ml-auto fa fa-angle-right"></i></div>
12
</li>
13
<li>
14
<div class="btnBorder flex">Widgets <i class="ml-auto fa fa-angle-right"></i></div>
15
</li>
16
<li>
17
<div class="btnBorder flex">Footer <i class="ml-auto fa fa-angle-right"></i></div>
18
</li>
19
</ul>
20
</div>
Note: The problem when using .next()
if the element has <!-- -->
or </br>
it will not select the correct element .. So you can use .closest().find()
you’ll find it in my code above