I'm writting a dropdown menu and I wanted to have the dropdown being controlled by javascript.
My dropdown has the sub menu hidden of sight max-height: 0px; and when the correspondent anchor tag is clicked, I change its max-height parameter to 400px, using the following function:
function drop_down(name) {
document.getElementById(name).style.maxHeight = "400px";
}
So far so good. The problem is that the element's max-height, stays at 400px and the sub menu does not hide. So I thought that I should target the click of the mouse and when this happens check if there is any element with 400px and change it back to 0.
$('html').click(function() {
var max_h = document.getElementsByClassName("nav_content");
var i;
for(i = 0 ; i < max_h.length ; i++)
{
if(max_h[i].style.maxHeight == "400px")
{
max_h[i].style.maxHeight = "0px";
}
}
});
What happens is that this function tracks every click, even the one used to display the sub menu. So my question is: is there a way to only activate the second function after I clicked my sub-menu? Because I always want the click that comes after the menu is displayed to close the sub menu.
HTML:
<body>
<div class="nav_container">
<nav class="nav_main">
<div class="logo">
<a href="#">
<img src="../majo.png" alt="logo">
</a>
</div>
<ul class="nav" id="nav">
<li>
Home
</li>
<li>
Consultas
<div id="nav_consul" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Informação Dia a Dia
</li>
<li>
Totais Mensais
</li>
<li>
Tarifário Atual da Rede
</li>
<li>
Data específica
</li>
<li>
Atividade do Sistema
</li>
<li>
Coimas
</li>
</ul>
</div>
</div>
</li>
<li>
Simulações
<div id="nav_simul" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Criar tarifa Simples
</li>
<li>
Criar tarifa Complexa
</li>
<li>
Simular com Nova Tarifa
</li>
</ul>
</div>
</div>
</li>
<li>
Preferências
<div id="nav_prefs" class="nav_content">
<div class="nav_sub">
<ul>
<li>
Lista de acessos
</li>
<li>
Alterar Password
</li>
<li>
Alterar Dados de Conta
</li>
</ul>
</div>
</div>
</li>
<li>
Log Out
</li>
</ul>
</nav>
</div>
<div id="content_main">
</div>
<footer></footer>
<script src="../js/jQuery.js"></script>
<script src="../js/user_menu.js"></script>
<script src="../js/user_nav.js"></script>
<script src="../js/user_clear_sub_menu.js"></script>
</body>
Here is an easy solution:
Create the following CSS-Styles:
.nav_content.visible {
max-height: 400px;
}
.nav_content.invisible {
max-height: 0px;
}
Set the overflow property for your nav_content to hidden:
.nav_content{
overflow: hidden;
}
Now add the class invisible to your submenus, if you want them to be invisible by default (you can do this manually in the markup or by js code):
Manually e.g.:
<div id="nav_prefs" class="nav_content invisible">
or by code (after the elements have been loaded):
$(".nav_content").addClass("invisible);
Now, if you just need to adjust your drop_down function to toggle the element's invisible/visible class:
function drop_down(dropdownID){
$('#'+dropdownID).toggleClass("visible invisible");
}
UPDATE: To make all visible submenus disappear when clicked elsewhere use this piece of code, when the window is loaded:
$(document).on('click', function (e) {
if (!$(e.target).is('.nav_item') && !$(".nav_item").has(e.target).length !== 0) {
$('.nav_content.visible').toggleClass("visible invisible");
}
});
If you only want to have one submenu visible at a time, you can use this version of your drop_down function:
function drop_down(dropdownID) {
$('.nav_content.visible').toggleClass("visible invisible");
$('#' + dropdownID).toggleClass("visible invisible");
}
A working fiddle can be found here
EDIT: Since you used jQuery in your original code, I assumed the answer can use jQuery too
You'll want to create a click handler on your document, then check the target of the click. If the target of the click has a certain class, use the menu behavior. If not, or if it's a sub-menu, close the menu.
Here's a question with multiple examples:
How do I close menu on click and when the user clicks away?
Also, I'd recommend not using max-height to hide and show. Since you're using jquery already, you could just use hide() and show().
One more thing: since you're using jquery already, you don't need to use these calls: document.getElementById(name). You can do a $("#yourId") or for document.getElementsByClassName("nav_content"); you can use $(".your-class")
It looks like you attached click event to entire document. I think you need to change only $('html').click(function() { to something like $('sub-menu-selector').click(function() { to
only activate the second function after I clicked my sub-menu
Aside to that, since it's only piece of jQuery and if you're not using it elsewhere, I would replace this with addEventListener and attachEvent, but maybe that's just me :)
In that case you can use jQuery.not() method to exclude the dropdown menu from your jQuery selection, here's what you need :
$('html').not(document.getElementsByClassName("nav_container")[0]).click(function() {
//As you can pass an element to it
You can also use the :not in your first selector like this:
$('html:not(div.nav_container))
Related
<li>
<div id="lineop1"><h3>Softshell</h3></div>
</li>
<li>
<div id="lineop1"><h3>Option</h3></div>
</li>
<li>
<div id="lineop1"><h3>Option 1</h3></div>
</li>
I need to show which one h3 tag is clicked to show active
You need to do it like below:-
$(document).ready(function(){
$('.lineop1 a h3').click(function(e){
e.preventDefault(); // to prevent page refresh with new url
$('h3').removeClass('active'); // remove active class from other h3 tag
$(this).addClass('active'); // add active class to current clicked tag
});
});
.active{
color:green;
font-size:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
<div class="lineop1"><h3>Softshell</h3></div>
</li>
<li>
<div class="lineop1"><h3>Option</h3></div>
</li>
<li>
<div class="lineop1"><h3>Option 1</h3></div>
</li>
Note:- id need to be unique per element. so convert id to class around <div's>
And if you want that after click on h3 when page refresh, then also the corresponding h3 tag have the active class, then you have to use localstorage concept like below:-
jQuery:-
$(document).ready(function(){
$('ul li').eq( localStorage.parent ).find('h3').addClass('active');
$('.lineop1 a h3').click(function(e){
var pagename = $(location).attr("href").split('/').pop();
localStorage.parent=$(this).closest('li').index();
});
});
Html:-
<ul>
<li>
<div class="lineop1"><h3>Softshell</h3></div>
</li>
<li>
<div class="lineop1"><h3>Option</h3></div>
</li>
<li>
<div class="lineop1"><h3>Option 1</h3></div>
</li>
</ul>
I have tested it on localhost at my end and working perfectly fine.
add a click handler to h3. Add class active to it.
$(document).ready(function(){
$(document).on('click','h3',function(){
$('h3').removeClass('active');
$(this).addClass('active');
});
});
.active{
color:#ff00eb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li>
<div id="lineop1"><h3>Softshell</h3></div>
</li>
<li>
<div id="lineop1"><h3>Option</h3></div>
</li>
<li>
<div id="lineop1"><h3>Option 1</h3></div>
</li>
Edit: its always good practice to attach click event to the closest unique parent element. so I have included $(document).On.
Follow this link to see working of Direct Vs Deletegated Events
So essentially I want to keep this as simple as possible, meaning no jquery or bootstrap etc... just straight javascript, HTML and CSS. This is what I have so far
Javscript:
var menuOptions= document.getElementsByClassName("nav");
var hamburger= document.getElementById("nav-btn");
function myFunction() {
hamburger.onclick= menuOptions.style.visibility= 'visible';
}
HTML:
<HTML>
<button onclick="myFunction()">
<span id="nav-btn">
<image src="Menugreen.png" alt="collapsable menu"/>
</span>
</button>
<div class="nav">
<ul>
<li id="Programs"> Programs </li>
<li> T-Shirts </li>
<li id="About"> About </li>
</ul>
</div>
</HTML>
CSS:
.nav {
visibility: hidden;
}
Besides just giving me a solution I would highly appreciate it if you could explain why my current method does not work and why yours does. Thanks in advance!
Two problems:
getElementsByClassName() returns a list, not a single element (though the list may contain just a single element), and that list doesn't have a .style property. You can use menuOptions[0] to access the first (and in this case only) element in the list.
You don't want to say hamburger.onclick= inside your function, because that would be assigning a new onclick handler but your function is already being called from the onclick attribute of your button. (Also, if you were trying to assign a new click handler you'd want hamburger.onclick = function() { /* something */ }.)
So the minimum change to your existing code to get it to work would be to change this line:
hamburger.onclick= menuOptions.style.visibility= 'visible';
...to this:
menuOptions[0].style.visibility = 'visible';
In context:
var menuOptions= document.getElementsByClassName("nav");
var hamburger= document.getElementById("nav-btn");
function myFunction() {
menuOptions[0].style.visibility = 'visible';
}
.nav {
visibility: hidden;
}
<HTML>
<button onclick="myFunction()">
<span id="nav-btn">
<image src="Menugreen.png" alt="collapsable menu"/>
</span>
</button>
<div class="nav">
<ul>
<li id="Programs"> Programs </li>
<li> T-Shirts </li>
<li id="About"> About </li>
</ul>
</div>
</HTML>
If you want repeated clicks on the button to toggle the menu display on and off then you can test the current visibility:
menuOptions[0].style.visibility =
menuOptions[0].style.visibility === 'visible' ? '' : 'visible';
Expand the following to see that working:
var menuOptions= document.getElementsByClassName("nav");
var hamburger= document.getElementById("nav-btn");
function myFunction() {
menuOptions[0].style.visibility =
menuOptions[0].style.visibility === 'visible' ? '' : 'visible';
}
.nav {
visibility: hidden;
}
<HTML>
<button onclick="myFunction()">
<span id="nav-btn">
<image src="Menugreen.png" alt="collapsable menu"/>
</span>
</button>
<div class="nav">
<ul>
<li id="Programs"> Programs </li>
<li> T-Shirts </li>
<li id="About"> About </li>
</ul>
</div>
</HTML>
There are a few reasons why your current setup does not function:
Document#getElementsByClassName returns a collection, and you are treating the result like a DOM element. You need to access an index like [0] to get an actual element.
Your toggle button only works one way, because visibility is set to visible but never set back to none when clicked again.
In myFunction, hamburger.onclick should not be assigned to the expression you chose. I am not sure why you tried to assign another click handler, but in order to make that work you would have needed to set it to a function () { ... }.
Now for my advice:
Use CSS classes to control whether the menu is hidden or not, rather than messing around with the style property in your JS. You can use the classList property of DOM elements to .add(), .remove(), and .toggle() a specific class when myFunction is run. I have chosen to use toggle because I think that most suits your use case.
Use element.addEventListener instead of HTML attributes like onclick.
Snippet:
var menuOptions = document.getElementsByClassName("nav")[0]
var hamburger = document.getElementById("nav-btn")
hamburger.parentNode.addEventListener('click', function myFunction() {
menuOptions.classList.toggle('hidden')
})
.nav.hidden {
visibility: hidden;
}
<button>
<span id="nav-btn">
<img src="Menugreen.png" alt="collapsable menu"/>
</span>
</button>
<div class="nav hidden">
<ul>
<li id="Programs"> Programs </li>
<li> T-Shirts </li>
<li id="About"> About </li>
</ul>
</div>
I have this html code
<div id="left-container" class="w3-container w3-left">
<div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
<h1>Give</h1>
<h3>Selected Definition:</h3>
<ul style="display:none;">
<li> offer in good faith </li>
<li> inflict as a punishment </li>
<li> afford access to </li>
</ul>
</div>
<div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
<h1>Up</h1>
<h3>Selected Definition:</h3>
<ul style="display:none;">
<li> to a higher intensity </li>
<li> to a later time </li>
<li> used up </li>
</ul>
</div>
</div>
<div id="right-container" class="w3-container w3-right"></div>
I want the user, once he click on one of the wordDiv's, to be able to see the potential definitions of that word in the right container (which are found in the "ul" element of each "wordDiv"), select one of the definitions, then I want to display the selected definition in the original wordDiv in the left-container.
You can found Jsfiddle Demo Here
A solution using jQuery. Updated Fiddle
$(function() {
$('.wordDiv').click(function() {
var txt = $(this).find('ul').html();
$('#right-container').html('<ul>' + txt + '</ul>')
})
})
Please check this fiddle
I have added li elements to another div based on the div which you are selected.
You can use the jQuery this variable in the click function, here is a working jQuery example of your request Updated Fiddle
It puts the li elements in the right div AND adds the onclick listener, which has the knowlege of its origin ;)
$('h1').click(function(){
var origin=$(this);
$(this).siblings('ul').children().click(function(){
$(this).parent().hide();
$(origin).parent().append(this);
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})
$(this).siblings('ul').show();
$("#right-container").append($(this).siblings('ul'));
})
$('ldi').click(function(){
$(this).parent().hide();
$(this).parent().parent().append(this);
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})
I'm trying to get my responsive navigation to collapse when clicking a navigation item (link).
This is my navigation:
<nav class="nav">
<ul>
<li class="nav-item">Overview</li>
<li class="nav-item">Amenities</li>
<li class="nav-item">Residences</li>
<li class="nav-item">Neighborhood</li>
<li class="nav-item">Availability</li>
<li class="nav-item">Contact</li>
<li class="btn login">Login</li>
<li class="nav-toggle"></li>
</ul>
</nav>
Here's how the responsive nav gets expanded:
<script>
function myFunction() {
document.getElementsByClassName("nav")[0].classList.toggle("responsive");
}
</script>
I'm not sure why you're mixing old school list tags with the modern Nav because you don't need them.
If you want the menu to collapse upon selection you can use this neat technique:
<nav style="position:absolute; left:20px; top:50px;">
<div onclick="TheBox.removeAttribute('open');">
<details id="TheBox"><summary>Choices</summary>
Home<br>
About<br>
Products<br>
Services<br>
Contact
</div></details></nav>
It looks like you want to hide the navigation when the toggle link is clicked. If so, I would do the following. Note that your <a> tags were outside the <li> tags, I've moved them inside.
<nav id="nav">
<ul>
<li class="nav-item">Overview</li>
<li class="nav-item">Amenities</li>
<li class="nav-item">Residences</li>
<li class="nav-item">Neighborhood</li>
<li class="nav-item">Availability</li>
<li class="nav-item">Contact</li>
<li class="btn login">Login</li>
<li class="nav0item">Toggle</li>
</ul>
</nav>
I would target by ID and not class, and set the display to none.
<script type="text/javascript">
function collapseNav() {
document.getElementById('nav').style.display = "none";}
</script>
Since your toggle is on a <li> inside the nav, your navigation menu (and the toggle) will be hidden when activated. So, I'd make a way to show it again. You could, for instance, add this function in your JS.
function showNav() {
document.getElementById('nav').style.display = "block";}
And then add a link somewhere for the user to show the menu again.
<button onclick="showNav();" >Show Menu</button>
If you go that route, I'd also hide the Show Menu button by default by adding id="shownav" style="display: none;" to hide it initially. And then have your collapseNav function also show the button:
document.getElementById('shownav').style.display = "block";
Thank you for your responses.
This is what I was looking for:
$(document).ready(function(){
$("li.nav-item a, .logo").click(function(){
$("nav").removeClass("responsive");
});
});
Now the "responsive" class gets removed when clicking on a navigation item or the logo, so my navigation returns to collapsed mode.
So I've got 2 <ul> containers each with id's. Inside of them are a list of <li> elements.
The first <ul> is <ul id="coaches-list">. The second is <ul id="players-list">.
There are tags within each <li> that have an id called close (which is a link that I'm using as my selector), which will delete each <li> node once clicked. I'm trying to target each <ul> container to see where it is coming from.
My HTML is:
<!-- coaches box -->
<div class="box">
<div class="heading">
<h3 id="coaches-heading">Coaches</h3>
<a id="coaches" class="filter-align-right">clear all</a>
</div>
<ul id="coaches-list" class="list">
<li><span>Hue Jackson<a class="close"></a></span></li>
<li class="red"><span>Steve Mariuchi<a class="close"></a> </span></li>
</ul>
</div>
<!-- players box -->
<div class="box">
<div class="heading">
<h3 id="players-heading">Players</h3>
<a id="players" class="filter-align-right">clear all</a>
</div>
<ul id="players-list" class="list">
<li><span>Steve Young<a class="close"></a></span></li>
<li><span>Gary Plummer<a class="close"></a></span></li>
<li><span>Jerry Rice<a class="close"></a></span></li>
</ul>
</div>
My remove tag function in jQuery is:
function removeSingleTag() {
$(".close").click(function() {
var $currentId = $(".close").closest("ul").attr("id");
alert($currentId);
// find the closest li element and remove it
$(this).closest("li").fadeOut("normal", function() {
$(this).remove();
return;
});
});
}
Whenever I click on each specific tag, it's removing the proper one I clicked on, although when I'm alerting $currentId, if I have:
var $currentId = $(".close").closest("ul").attr("id");
It alerts 'coaches-list' when I'm clicking on a close selector in both <ul id="coaches-list" class="list"></ul> and <ul id="players-list" class="list"></ul>
If I change that to:
var $currentId = $(".close").parents("ul").attr("id");
It has the same behavior as above, but alerts 'players-list', instead.
So when using closest(), it's returning the very first <ul> id, but when using parents(), it's returning the very last <ul> id.
Anyone know what is going on with this whacky behavior?
It's expected behavior.
You should use:
var $currentId = $(this).closest("ul").attr("id");
$(this) points at the clicked .close.
$(".close") points at the first one found.
It's because you run that selector from click handler you should use this instead:
var $currentId = $(this).closest("ul").attr("id");
Try using this function to get the parent:
var $currentId = $(this).parents().first();
I've never used the .closest() function but according to jQuery what you have specified should work. Either way, try that out and tell me how it goes.
You also need to make it so that it selects the current element by using $(this)