detecting the last list item in jquery/javascript - javascript

I have a set of tab (main-tabs) on a website and each tab has another set of tabs (sub-tabs).
I want to use arrow keys on a keyboard to navigate the tabs, instead of a mouse.
These tabs are just HTML list items <li>
When I reach the last sub-tab with the arrow key, I want it to go back to the next main tab so it can display its own sub-tabs, and carry on the navigation inside it.
My question is, how can I detect, in jQuery/javascript, when I've reached the last list item (tab) using the arrow keys i.e. the right arrow key?
Many Thanks

You might be able to use either the :last or :last-child selectors in jQuery. Depending on how your <li> tags are nested, you might also have to use the children() function along with it.
For example, let's say you have the following markup:
<ul id="nav">
<li>List item</li>
<li>List item with sub items
<ul>
<li>Sub list item</li>
</ul>
</li>
</ul>
This would select the last top-level <li>
$('ul#nav > li:last').css('border', '1px solid red');
This would select the last <li> traversing the DOM downward. In this case it's the <li> with text "Sub list item"
$('ul#nav li:last').css('border', '1px solid red');
This would select any <li> tags that are the last child of their parent
$('ul#nav li:last-child').css('border', '1px solid red');

var maintabs = $('.maintab'),
active_maintab_eq = 0,
active_subtab_number = 1;
$(document).keyup( function(e){
if (e.which == 39) {
// right arrow key pressed
if ( active_subtab_number == maintabs.eq(active_maintab_eq).find('li').length ) {
// go to next main-tab
// and reset active sub-tab counter
++active_maintab_eq;
active_subtab_number = 1;
} else {
++active_subtab_number;
}
}
});
Some thing like this, I guess.

You can use .length to find out if a jQuery selector found anything:
var nextSubTab = $(currentSubTab).next("li");
if (nextSubTab.length == 0) {
// oops, end of this tab, switch to next tab
}

Related

Open/Close submenu when clicking the item name

I am having problems with the menu part of a wordpress site (salient theme), when i am on mobile, i open the menu with the hamburger button and have several options, some with sub menus, so the items with sub menus only open when clicking the little arrow icon to the right of the item, i am trying to get it to open also when you click on the item itself by making it so when you click the item it triggers a click on the arrow
here is the html of the menu
and here is the javascript i am doing to get it to work(only doing it for the first item with submenu here), i am new to javascript but for what i've seen i think this should work (i am using the Code Snippets
plugin for wordpress)
<?php
add_action( 'wp_footer', function () { ?>
<script>
var el = (document.querySelector('.menu-item.menu-item-type-custom.menu-
item-object-custom.menu-item-has-children.menu-item-5812 a'));
console.log(el);
var el2 =(document.querySelector('.menu-item.menu-item-type-custom.menu-
item-object-custom.menu-item-has-children.menu-item-5812 span'));
console.log(el2);
el.onclick = function()
{
$el2.click();
};
</script>
<?php } );
?>
SOLUTION:
aside from the answear by Alvaro Montoro i needed to encapsulate everything inside an eventListener with DomLoaded, here is the final code
add_action( 'wp_footer', function () { ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elSupervivencia = document.querySelector('#slide-out-widget-area > div >
div.inner > div > ul:nth-child(1) > li.menu-item.menu-item-type-custom.menu-
item-object-custom.menu-item-has-children.menu-item-5812 > a');
console.log(elSupervivencia);
var elSupervivenciaFlecha = document.querySelector('#slide-out-widget-area >
div > div.inner > div > ul:nth-child(1) > li.menu-item.menu-item-type-
custom.menu-item-object-custom.menu-item-has-children.menu-item-5812 .ocm-
dropdown-arrow i');
console.log(elSupervivenciaFlecha);
elSupervivenciaFlecha.onclick = function() {
console.log("Clicked on the span");
}
elSupervivencia.onclick = function(e)
{
e.preventDefault();
elSupervivenciaFlecha.click();
};
});
</script>
<?php } );
For what you seem to want, you almost have it. The only thing that seems to be missing is to prevent the default behavior when you click on the link (which could be a potential problem as pointed on the comments above, because the linked page may be innaccessible through the menu now).
With .preventDefault() you will prevent the default action for that element for that event, so you would just need to add that:
var el = (document.querySelector('.menu-item.menu-item-type-custom.menu-item-object-custom.menu-item-has-children.menu-item-5812 a'));
console.log(el);
var el2 = (document.querySelector('.menu-item.menu-item-type-custom.menu-item-object-custom.menu-item-has-children.menu-item-5812 span'));
console.log(el2);
el2.onclick = function() {
console.log("Clicked on the span");
}
el.onclick = function(e) {
e.preventDefault();
el2.click(); // removed the $
};
<ul class="menu">
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-5812">
Supervivencia
<ul class="sub-menu">
<li>Supervivencia 1</li>
<li>Supervivencia 2</li>
<li>Supervivencia 3</li>
</ul>
<span class="ocm-drowndown-arrow" style="top: 17.5px">
<i class="fa-angle-down"></i>
</span>
</li>
</ul>
As they pointed in the comments, that may not be too usable, as the linked page is no longer accessible on the menu, you may want to add some conditions (checking for window size or a variable/class that indicates that the mobile menu is active) to perform that preventDefault().
Apart from that, you may want to consider changing the selector for el and el2, as they are not specific and could match more than one element. I know you are using querySelector so only the first element that matches the selector will be returned, which should not be a problem for el but could be problematic with el2 (because the a could be a child span that would be selected over the sibling one that is the one you want.)

Closing one element when opening another within the same loop using Javascript

first time on here so i'll try my best to explain what I'm asking.
So I have 3 list items with the same class name. I've put them in a looping function so that when you click on one it will display a sub set of list items for that specific list item. I also have them inside an if statement that adds a new class name to the specific list item that was clicked. It allows opening and closing of the sub list items when you click the corresponding parent element.
My question is; how can I use this same principle of checking for the additional class name, when the user clicks any of the list items. In other words, I am trying to code it in a way that will allow me to close any of the open sub list items when the user clicks a new list item.
This is what I came up with but it doesn't know what button[i] is when I include it within the "click" function. What I was trying to do with this code is to take whatever list item was clicked, and then check the previous and next iterations of the class name "button" to see if any of the contain also contain the class name "clicked.
HTML
<div class="main">
<ul>
<li>One
<ul>
<li>One-1</li>
<li>One-2</li>
</ul>
</li>
<li>Two
<ul>
<li>Two-1</li>
<li>Two-2</li>
</ul>
</li>
<li>Three
<ul>
<li>Three-1</li>
<li>Three-2</li>
</ul>
</li>
</ul>
</div>
CSS
.main ul ul {
display: none;
}
.main ul ul li {
display: block;
}
Javascript
var button = document.getElementsByClassName("button");
for (i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
var prevItem = button[i - 1];
var nextItem = button[i + 1];
if (prevItem.className !== "button") {
prevItem.className = "button";
prevItem.nextElementSibling.style.display = "none";
}
if (nextItem.className !== "button") {
nextItem.className = "button";
nextItem.nextElementSibling.style.display = "none";
}
if (this.className === "button") {
this.className += " clicked";
this.nextElementSibling.style.display = "block";
}
});
}
I am wanting to make this code usable no matter how many list items you add. So checking exactly button[0] button[1] and button[2] wasn't really an option, but I can see how button[i + 1] might not check every list item after it but rather just the next one. I tried adding another loop but ran into similar issues. anyway that's why I'm here. Thanks for any help in advance.
Since I am not sure whether I understood your question correctly, I quickly rephrase it in my own words.
Question: "I have an arbitrary number of list elements, of which each contains a button and a nested list. The button is always visible, the nested list is hidden by default. When the user clicks on a button, the corresponding nested list should be shown. At the same time, all other shown nested lists should be hidden again. How can I achieve this?"
The original HTML looks fine:
<div class="main">
<ul>
<li>One
<ul>
<li>One-1</li>
<li>One-2</li>
</ul>
</li>
<li>Two
<ul>
<li>Two-1</li>
<li>Two-2</li>
</ul>
</li>
<li>Three
<ul>
<li>Three-1</li>
<li>Three-2</li>
</ul>
</li>
</ul>
</div>
The CSS I did not fully understand, but I suggest the following:
.main ul ul {
display: none;
}
.main li.is-active ul {
display: block;
}
.main ul ul li {
display: block;
}
By adding the "is-active" class to an LI element, it is shown. This way, the CSS controls the visibility.
For the JavaScript part, I suggest this:
const buttonElements = Array.from(document.querySelectorAll('.button'));
buttonElements.forEach(buttonElement => {
buttonElement.addEventListener('click', () => {
const activeElements = Array.from(document.querySelectorAll('.is-active'));
activeElements.forEach(activeElement => {
activeElement.classList.remove('is-active');
});
buttonElement.parentElement.classList.add('is-active');
});
});
This solution assumes you can use newer versions of JavaScript/ECMAScript. Overall, it makes use of const and arrow functions.
First, we get all elements with the class "button" by using document.querySelectorAll(). Since the result is a NodeList and no array, we convert it using Array.from(). Afterwards, we loop through the array by using Array.prototpye.forEach(). We add an event listener for the "click" event. When a button is clicked, we search for all elements with the "is-active" class and for each one remove it. Finally, we add the "is-active" class to the parent element of the clicked button using Node.prototype.parentElement().
Here is another solution that works in older browsers:
var buttonElements = document.getElementsByClassName('button');
for (var i = 0; i < buttonElements.length; i++) {
buttonElements[i].addEventListener('click', function(event) {
var activeListElements = document.getElementsByClassName('is-active');
for (var i = 0; i < activeListElements.length; i++) {
activeListElements[i].setAttribute('class', '');
}
event.target.parentNode.setAttribute('class', 'is-active');
});
}
This is pretty much the same as the other approach but works with older versions of JavaScript.
Generally, the idea is to focus on an arbitrary sum of elements instead of an array with a specific length. In natural language something like: "Give me all buttons. For every button, add an event listener. When a button is clicked, give me all active list elements and remove their active status. Then, mark the list item above the button as active".
Hope this helps

Sometimes on click executed twice

I'm having a very strange problem. Basically I have created a menu in wordpress that has parent, childs, subchilds and inside some posts.
I wrote a jquery script that adds a highlight class on the <li> in order to expand the <ul> which is inside the <li>. the format of the list is the following
<li class"menu-item-has-children"><a>Parent</a>
<ul>
<li class="menu-item-has-children"><a>Child</a>
<ul>
<li class="menu-item-has-children"><a>Sub Child</a>
<ul>
<li><a> post</a></li>
<li><a> post 2 </a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
So I wrote the following script to add highlight class to expand the sub child of the clicked <li>. When I'm clicking on any <li> of parent,child, sub child is working fine but when I click on the posts it removes the highlight class from the parent <ul> instead of taking me to the page of the clicked post.
I did a console log of $(this) and when click on any parent, child,sub child it shows me <ul> that has, but when I click on any posts it shows me first the <a> tag that it has followed by the parent <ul>. Does anyone know why?
Here is my jquery code
$(document).unbind("click").on('click',".sidebar-right li",function(e){
var found = false;
var tmp = String($(this).val());
if (tmp.indexOf("ul") != -1){
found = true;
}
if (($(this).hasClass("menu-item-has-children")) && (!$(this).children('ul').hasClass("highlight")))
{
$(this).children("a").addClass("highlight_icon");
$(this).children('ul').addClass("highlight");
return false;
}
else if (($(this).has("a") && ($(this).has("ul"))) && (!$(this).children('ul').hasClass("highlight")))
{
return true;
}
else if ($(this).children('ul').hasClass("highlight"))
{
$(this).children('a').removeClass("highlight_icon");
$(this).children('ul').removeClass("highlight");
return false;
}
else
{
return true;
}
});
Here is the console log data
Child Parent etc
Post click
SOLUTION: event.stopPropagation() as #mohamed-yousef said
try
$(".sidebar-right").on('click',".sidebar-right li", function(){
....});

Hide <h3> when all ul>li of group does not contain filter term

I've created a small script that filters my ul with a nested ul inside of it. The only issue with my script is I want to hide the title of the nested ul if none of the li's contain the search term, but I am not sure how to go about checking the li's of each "group" as opposed to each li individually. The way it stands, it will display the title if it finds an li in the group matching the search term, but it will immediately turn around and hide the title if the same group contains an li that DOES NOT contain the search term. I know what I'm doing wrong, but I am not as skilled in jquery and cannot seem to visualize how to go about this.
Any help would be great. My code is below:
HTML:
<div id="sitemap">
<h3>Hospital Data Solutions Interactive Site Map</h3>
<hr/>
<p id="header"><input type="text" placeholder="Filter Site Map"> - Use this field filter our list of databases: Search by Topic or Topic Subgroup</p>
<ul id="toplist">
<li class="group">
<h3 class="sTitle">Available Beds - <a style="font-size:18px;">Go to Section</a></h3>
<ul class="sublist">
<li>General</li>
<li>ICU</li>
<li>CCU</li>
<li>BICU</li>
<li>SICU</li>
<li>Other</li>
<li>Hospice</li>
<li>Total</li>
</ul>
</li>
<hr/>
<li class="group">
<h3 class="sTitle">Discharges - <a style="font-size:18px;">Go to Section</a></h3>
<ul class="sublist">
<li>Medicare</li>
<li>Medicaid</li>
<li>Other</li>
<li>Total</li>
</ul>
</li>
</ul>
</div>
Jquery:
$(function(){
$('input[type="text"]').keyup(function(){
var searchText = $(this).val().toLowerCase();
$('.sublist>li').each(function(){
var currentLi = $(this).text().toLowerCase();
if(currentLi.search(searchText) != -1){
$(this).slideDown();
$(this).closest('.group').children('.sTitle').show();
} else { $(this).slideUp(); $(this).closest('.group').children('.sTitle').hide();}
});
});
});
First, select the .sublist elements instead of the lis.
Then iterate that collection using .each(), and use .children() to test each li like you currently are, except use .filter() instead of .each(). This will give you a collection as a result. If the collection is empty, there were no matches. If not, then there was a match.
$('input[type="text"]').keyup(function(){
var searchText = $(this).val().toLowerCase();
$('.sublist').each(function(i, sub){
var matches = $(sub).children().filter(function(i, li) {
return $(li).text().toLowerCase().search(searchText) != -1;
});
if (matches.length) {
$(sub).slideDown().prev().show();
} else {
$(sub).slideUp().prev().hide();
}
});
});
Now the slideDown/Up and show/hide are happening once per sublist instead of on every child li. And I just used .prev() to get back to the h3 element.
If you're going to be hiding those list items that don't match your search you're going to want to deal with them individually anyway, so I wouldn't abandon that approach. So you just need a way to check to see if the term was found somewhere in the search of the nested list. Here's what I might do to utilize what you already have.
After you capture the search term, loop through each of the sublists and set a flag to false; this will be where we capture whether there were any matches. Then loop through that sublist's items, and if you find a match set the flag to true, showing or hiding the item as necessary. Then, after you've checked all the items show or hide the heading based on that flag. It might look something like this:
$('.sublist').each(function(){
found = false;
$(this).children("li").each( function() {
var currentLi = $(this).text().toLowerCase();
if(currentLi.search(searchText) != -1){
$(this).slideDown();
found = true;
} else {
$(this).slideUp();
}
});
if(found) {
$(this).closest('.group').children('.sTitle').show();
} else {
$(this).closest('.group').css("list-style-type", "none");
$(this).closest('.group').children('.sTitle').hide();
}
});
I added a css line to show/hide the header's disc to avoid having that hanging there if everything else disappears. Hope this helps! Let me know if you have any questions.

Jquery to copy first link to second ul and then change class of first link

Short question:
http://jsfiddle.net/wF4FH/2/
What I want is for Page1 to be right above Page2 and Page10 above Page 20 before I change the classes. This should work for any number of elements.
The code provided gives an "Uncaught TypeError: Object # has no method 'append' ".
Long question:
I'm having problem finding the correct way to insert an li element based on the first link. The problem is I cant use id's on my markup so I have to "walk through" each class and check for names. I might just make this a lot more complicated than it is because my first two solutions didn't work the way I thought they would.
html
<ul class="nav">
<li class="active">
Start
</li>
<li class="has-child">
page1
<ul class="">
<li>
page2
</li>
</ul>
</li>
<li class="has-child">
page10
<ul class="">
<li>
page20
</li>
<li>
page30
</li>
</ul>
</li>
javascript
//Copy first link to child ul li
var pageLinks = $("li.has-child > a:first-child");
if (pageLinks != null) {
//var dropdownMenus = $("li.dropdown > a:first-child");
for (var i = 0; i < pageLinks.length; i++) {
for (var x = 0; x < pageLinks.length; x++) {
if (pageLinks[i].innerHTML === pageLinks[x].innerHTML) {
pageLinks[x].childNodes.append(pageLinks[i]);
}
}
}
}
//Change css classes
$("li.has-child").attr('class', 'dropdown');
$(".dropdown ul").addClass("dropdown-menu");
$(".dropdown a").attr("href", "#").addClass("dropdown-toggle").attr('data-toggle', 'dropdown');
strong text
What I want is for Page1 to be right above Page2 and Page10 above Page 20 before I change the classes. This should work for any number of elements.
When they are copied to the inner ul I change the top level menu item to a different class to work as a clickable dropdown men item.
The code provided gives an "Uncaught TypeError: Object # has no method 'append' ".
It is the navigation of a cms I cant change the markup on.
try this:
$links = $('li.has-child').children('a:first-child');
if($links.length > 0){
$links.each(function(i,link){
$(link).next().prepend($('<li></li>').append($(link)))
})
}
http://jsfiddle.net/wF4FH/6/
You need .clone() method to copy elements..
UPDATED
$links = $('li.has-child').children('a:first-child');
if($links.length > 0){
$links.each(function(i,link){
$(link).next().prepend($('<li></li>').append($(link).clone()))
})
}
http://jsfiddle.net/wF4FH/7/
When you have a jQuery object and you access it by numeric index, you're left with an HTML element. So $('body')[0] == document.body. This means that when you access pageLinks[x], you're really getting a raw element. This means that you want pageLinks[x].appendChild(pageLinks[i]);, not pageLinks[x].childNodes.append(pageLinks[i]);

Categories

Resources