Jquery li selector
I have this code and I need to get a script to work:
$(document).ready(function () {
$('.toggle').hide();
$('li.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide();
elem.toggle();
});
});
How do I make a selector for li.togglelink? Why is my script not working?
<ul id="main" class="horizontal">
<li class="togglelink">Lorem ipsum
<ul id="drop" class="toggle vertical">
<li>První</li>
<li>Druhý</li>
<li>První</li>
<li>Druhý</li>
</ul>
</li>
</ul>
One more import thing: how to hide the switch if not togglelink or toggle the hang?
source to share
you need to use .find()
instead .next()
because you are looking for a class inside .togglelink
. And you don't need to use e.peventDefault()
(unless you plan on adding links). You can also shorten your script:
$('.toggle').hide();
$('li.togglelink').on('click', function (e) {
var elem = $(this).find('.toggle').slideToggle();
});
You can also set .toggle
to display: none
in your CSS instead of being called $('.toggle').hide();
on page load:
source to share
Be careful with your markup, usually you have to use a link inside the element <li>
or you will need to customize the cursor via CSS. This is how I would do it:
Html
<ul id="main" class="horizontal">
<li id="togglelink">
<a href="#">Lorem ipsum</a>
<ul id="drop" class="toggle vertical">
<li>První</li>
<li>Druhý</li>
<li>První</li>
<li>Druhý</li>
</ul>
</li>
</ul>
Jquery
$('.toggle').hide();
$(function() {
$('#togglelink>a').click(function(e) {
$(this).find('.toggle').slideToggle();
return false;
});
});
source to share
This is because it .next()
selects 'siblings' and you are trying to select the "child" for which you would like, children()
or more generally .find()
:
$(document).ready(function () {
$('.toggle').hide();
$('li.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).find('.toggle')
$('.toggle').children().not(elem).hide();
elem.toggle();
});
});
In this case, it will toggle all the children .togglelink
except for the elements <ul>
that have a class toggle
. I'm not sure what the desired output is, but at least does something with .find()
instead of .next()
probably fixing it.
source to share
$(document).ready(function () {
$('.toggle').hide();
$('.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).find('.toggle')
$('.toggle').not(elem).hide();
elem.toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
How can I make selector for li.togglelink? Why my script not works?
<ul id="main" class="horizontal">
<li class="togglelink">Lorem ipsum
<ul id="drop" class="toggle vertical">
<li>První</li>
<li>Druhý</li>
<li>První</li>
<li>Druhý</li>
</ul>
</li>
</li>
</ul>
source to share