javascript - JQuery hiding a dropdown menu when clicking another element -
i have following html create dropdown menu:
<li class="user-section user-section-original"> <img class="user-image" src="{{ user.get_profile.avatar_small.url }}" height="30" width="30"/> <span class="name">{{ user.first_name }} {{ user.last_name.0}}.</span> </li> <li class="user-section-dropdown user-section hidden"> <img class="user-image" src="{{ user.get_profile.avatar_small.url }}" height="30" width="30"/> <span class="name">{{ user.first_name }} {{ user.last_name.0}}.</span> <a href="{% url logout %}" class="dropdown-item">log out</a> </li>
when user clicks menu, dropdown, , if user clicks again (or clicks anywhere outside of dropdown menu), hide again.
here have far:
$("#header li.user-section").click(function() { $("#header .user-section-dropdown").css('display', 'block'); $("#header .user-section-original").css('display', 'none'); });
this makes account dropdown appear when account section clicked. how make disappear when clicked again or section on page clicked?
you need add click listener whole document , hide dropdown if shown.
$(document).click(function() { if($("#header .user-section-dropdown").css('display') == 'block') { $("#header .user-section-dropdown").css('display', 'none'); $("#header .user-section-original").css('display', 'block'); } });
also, need modify original function handles both cases:
$("#header li.user-section").click(function(e) { if($("#header .user-section-dropdown").css('display') == 'none') { $("#header .user-section-dropdown").css('display', 'block'); $("#header .user-section-original").css('display', 'none'); e.stoppropagation() } else { $("#header .user-section-dropdown").css('display', 'none'); $("#header .user-section-original").css('display', 'block'); } });
e.stoppropagation() used not let document click handler called.
Comments
Post a Comment