BobbyJones BobbyJones - 4 years ago 323
Javascript Question

UL LI click is hiding the UL

I am trying to make a UL LI list such that when the word "LIST" is clicked on, the LI elements will be displayed and vice-versa. However, if an LI is clicked on the entire list gets hidden again. I'd like to make it such that if an LI is clicked on, it wont hide my list as I'd like to add functionality for the LI click later.

Here is the code in question:

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
ul {
list-style-type: none;
margin: 0;
padding: 0;
cursor: pointer;
}
ul li {
display: none;
}
ul li:before{ content:"- ";}
</style>

<script type="text/javascript">

window.onload = function() {

$('ul').click(function(){

if ($('ul > li').css('display') == 'none') {

$('ul > li').show();

}
else {
$('ul > li').hide()

}

});

}
</script>

</head>

<body>

<ul>
List
<li>1234</li>
<li>5678</li>
<li>0123</li>
</ul>


</body>

</html>

Answer Source

As pointed out above you can't just stick text in a ul like that. A ul should only have li elements within it. A cleaner approach is something like this that shows and hides the ul element instead of all the lis inside it with a control external to the ul.

Also as pointed out below there is a much better way to handle this all to make sure you aren't dealing with every ul on the page. By using class selectors and the built in jquery functions.

Fiddle: https://jsfiddle.net/erjfghf0/

HTML:

<a class="showHideLink">List</a>
<ul class="showHideList">
    <li>1234</li>
    <li>5678</li>
    <li>0123</li>
</ul>

JS:

$('.showHideLink').click(
    function (event) {
        $(this).next('.showHideList').toggle();
    }
);

CSS:

ul {
    display: none;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download