How to keep a menu-item selected in html with javascript - javascript

This is my html code. How can I keep a menu-item (link to another page) selected when I'am browsing ? I'd like to do it with javascript. Thank you in advance.
<ul class="header-menu" id="nav">
<li class="menu-item">HOME</li>
<li class="menu-item">NEWS</li>
<li class="menu-item">TOUR DATES</li>
<li class="menu-item">GALLERY</li>
<li class="menu-item">ABOUT</li>
</ul>

There are multiple ways to achieve that effect. Let's first state that you have an "active" class that you can use on the menu items that will make them pop out, how would you go about applying that class?
First of all, I would assign a specific class or id to all the menu items, to make them easy to reference within the css (or javascript).
Let's say that now your situation is like this:
<ul class="header-menu" id="nav">
<li class="menu-item home-item">HOME</li>
<li class="menu-item news-item">NEWS</li>
<li class="menu-item tour-item">TOUR DATES</li>
<li class="menu-item gallery-item">GALLERY</li>
<li class="menu-item about-item">ABOUT</li>
</ul>
Now, with javascript, you could do it like this:
// Get the page name
let pathArray = location.pathname.split("/");
let page = pathArray[pathArray.length-1];
// Get all menu items and convert them to an Array
let menuItems = document.querySelectorAll(".header-menu .menu-item");
menuItems = new Array(...menuItems);
let lookFor = "";
// Based on the page, set the variable lookFor as the identifying class
switch (page) {
case "home.html":
lookFor = "home-item";
break;
case "news.html":
lookFor = "news-item";
break;
// ...
}
// Get the element that contains the class
let item = menuItems.filter( (item) => item.classList.contains(lookFor) )[0];
// Set the "active" class on the element
item.classList.add("active");
Here you can check out a codesandbox with the working code.

Related

Select an item from a list with javascript

I am using javascrypt with selenium. I need to search and select one of the items in this list, but I am unable to select it. I can find it, but not select the element.
Please help me, thank you very much
var input = document.evaluate("//li[contains(., 'ATACAMA')]", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
You could try the following below:
var input = document.evaluate("//li[text()='ATACAMA']", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
So I don't have a clue about Xpath, but like you said, there is nothing stopping you from using querySelector or in this case querySelectorAll instead.
Here I create an array of all the li elements and use .find to get the element that has the text "Item 3" in it. I then click the element programmatically. All of the li elements have onClick event inline in the html.
Would this work for you?
let li_item = Array.from(document.querySelectorAll('li'))
.find(x => x.textContent === 'Item 3');
li_item.click();
function select(element, n) {
element.style.color = "red";
console.log(`${n} has been selected!`);
}
<ul>
<li onClick = "select(this, 1)">Item 1</li>
<li onClick = "select(this, 2)">Item 2</li>
<li onClick = "select(this, 3)">Item 3</li>
<li onClick = "select(this, 4)">Item 4</li>
<li onClick = "select(this, 5)">Item 5</li>
</ul>

How to iterate through <ul> child elements using DOM JS

So I have a menu, I want it to display information accordingly, for example:
<ul id="menu-list">
<li id="about-me">About Me</li>
<li id="skills">Skills</li>
<li id="experience">Experience</li>
<li id="education">Education</li>
<li id="projects">Projects</l>
<li id="contacts">Contacts</li>
</ul>
and on my JS file I did this in order to access "li" elements:
let navMenu = document.getElementById("menu-list");
let menuList = navMenu.getElementsByTagName("li");
let skillsButton = document.getElementById("skills");
let skillsEvent = document.getElementById('main-section-skills').hidden = true;
(text that will display on click is pre-set to hidden = true)
The goal is to iterate through "li" items to find which one of those has ".hidden = false" value and change it to ".hidden = true" so that when you click on different menu buttons, each button will so only relevant info and others that are not relevant will bi hidden.
Thanks for your help.
You can get the array of children using element.children
https://developer.mozilla.org/en-US/docs/Web/API/Element/children
for (let child of navMenu.children) {
your logic here
}
For checking the class you can use element.hasClass or even:
element.style.display = 'none'
element.style.display = 'block'

append / appendChild not working on all items

I'm trying to move all the list items from an list to another using only javascript but for some reason only half of them are actually moved.
Heres a working example of what I'm doing:
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
for (var x = 0; x < stores_li.length; x++) {
document.getElementById('hide').appendChild(stores_li[x]);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
What seems to be the problem?
getElementsByClassName returns a live list.
When you append the element to a different element, you change its position in the list.
So it starts off as:
1 2 3 4
Then you move the first one:
2 3 4 1
Then you access the second one … but the second one is now 3 because everything has shuffled down the list.
You could copy each element into an array (which will not be a live list) and then iterate over that array to move them (so they won't change positions as you go).
Alternatively, you could use querySelectorAll which returns a non-live list.
You should better use querySelectorAll than getElementsByClassName
var results_ul = document.getElementById('results');
var stores_li = document.querySelectorAll('.store-list-item');
stores_li.forEach((item)=>{
document.getElementById('hide').appendChild(item);
item.className += ' teste';
});
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Try use querySelectorAll . It'll returns a non-live list. That's what you need.
var stores_li = document.querySelectorAll('.store-list-item');
To increase more information:
Live : when the changes in the DOM are reflected in the collection. The content suffers the change when a node is modified.
Non-Live : when any change in the DOM does not affect the content of the collection.
document.getElementsByClassName() is an HTMLCollection, and is live.
document.querySelectorAll() is a NodeList and is not live.
In your code you are removing each element from the first list and inserting into the new list. After you remove 2 elements it will have only 2 elements in the first list but now you are searching the 3 rd index in the loop which is not there. So to make it work i have prepended each element from the last.
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
var hide_ul = document.getElementById('hide');
for (var x = 0, y = stores_li.length; x < y; x++) {
hide_ul.insertBefore(stores_li[y-x-1],hide_ul.firstChild);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Or you may want to clone the element with Jquery and you can push into the clonned ones then delete the orginals from top. I could not find any equivalent of clone() for js but if you want to check link is here
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
while(stores_li.length>0) {
document.getElementById('hide').appendChild(stores_li[0]);
stores_li[x].className += ' teste';
}

How to add a class to a class with Javascript not JQ

trying to figure out how to find a class and add a class to it using javascript. all example online are with id , I need to find the classs. Any idea guys?
I am adding a class once the page is loaded.
<nav class="menu custom-effect" id="customMenu">
<ul class="menu-list">
<li class="menu-item current_page_item">Home</li>
<li class="menu-item">Who we are</li>
<li class="menu-item">What we offer</li>
<li class="menu-item">Our news</li>
<li class="menu-item">Contact us</li>
</ul>
</nav>
<script>
document.addEventListener("DOMContentLoaded", function(){
// document.getElementById("current_page_item").classList.add( "current-page");
var element = document.getElementById("customMenu");
var elementClass = element.getElementsByClassName("current_page_item");
elementClass[0].ClassNames.add("extraClass");
console.log(element);
console.log(elementClass);
});
</script>
When you search for a class you get an array I understood and not just one element, so you need to referece the element u want as it picks up all the classes.
the answear to the code is
<script>
var element = document.getElementById("menu-main-menu");
var elementClass = element.getElementsByClassName("current_page_item");
elementClass[0].classList.add("foo");
</script>
classList implementation of these methods is super easy now that I understood the issue:
// adds class "foo" to el
el.classList.add("foo");
// removes class "bar" from el
el.classList.remove("bar");
// toggles the class "foo"
el.classList.toggle("foo");
// outputs "true" to console if el contains "foo", "false" if not
console.log( el.classList.contains("foo") );
// add multiple classes to el
el.classList.add( "foo", "bar" );

Cycling through a jQuery object with elements grouped together

I have a set of list items that contain nested lists, sort of like this:
<ul class="searchselectors">
<li class="group">Group name 1
<ul>
<li class="item selected">List item 1.1</li>
<li class="item">List item 1.2</li>
<li class="item">List item 1.3</li>
</ul>
</li>
<li class="group">Group name 2
<ul>
<li class="item">List item 2.1</li>
<li class="item">List item 2.2</li>
<li class="item">List item 2.3</li>
</ul>
</li>
<li class="group">Group name 3
<ul>
<li class="item">List item 3.1</li>
</ul>
</li>
</ul>
I want to cycle through all of the .item elements using up/down arrow keys (which I already have set up by using on('keydown') and catching key codes 38 and 40) and set .selected on the next item before or after the currently selected item, wrapping around to the top/bottom as necessary.
Using $().next() and $().prev() will not work, since it will only work on siblings, and not on a jQuery object such as $('.searchselectors .item').\
I was working on the same problem but in my project I'm using KnockoutJS. In fact, the original logic was written with pure jQuery and I refactored it with Knockout. Here's a solution for your problem using jQuery:
Fiddle - http://jsfiddle.net/6QN77/2/
I didn't spend too much time cleaning up the JavaScript, but I'm leaving that to you now.
HTML
<ul id="searchselectors">
<li class="group">Group name 1
<ul>
<li class="item selected">List item 1.1</li>
<li class="item">List item 1.2</li>
<li class="item">List item 1.3</li>
</ul>
</li>
<li class="group">Group name 2
<ul>
<li class="item">List item 2.1</li>
<li class="item">List item 2.2</li>
<li class="item">List item 2.3</li>
</ul>
</li>
<li class="group">Group name 3
<ul>
<li class="item">List item 3.1</li>
</ul>
</li>
</ul>
jQuery
$(function () {
var $menu = $("#searchselectors"),
$items = $menu.find(".item"),
$selectedItem = $menu.find(".selected"),
selectedIndex = $selectedItem.length - 1;
$(document).on("keydown", function (e) {
switch(e.keyCode) {
case 40: // down arrow
$selectedItem.removeClass("selected");
selectedIndex = (selectedIndex + 1) % $items.length;
$selectedItem = $items.eq(selectedIndex).addClass("selected");
break;
case 38: // up arrow
$selectedItem.removeClass("selected");
selectedIndex = (selectedIndex - 1) % $items.length;
$selectedItem = $items.eq(selectedIndex).addClass("selected");
break;
}
});
});
UPDATE: My solution revolves around getting a reference to a wrapper element (#searchselectors) and getting all the LI elements marked with the CSS class .item. Next I get a reference to the currently selected element and its index. Finally, the code listens to the down and up arrow keys being pressed (keydown), decrementing if going up and incrementing if going up. Cycling is achieved via the modulus operator. The selected item's CSS class is removed and put back. The selected item reference is used for performance reasons so I don't have to write $items.removeClass(".selected").eq(selectedIndex).addClass("selected");
In my quest to provide native JS answers to those looking for it, here is #Mario j Vargas' good answer adapted in native Javascript. It only takes 2 lines of extra code.
http://jsfiddle.net/kevinvanlierde/7tQSW/2/
Only putting the JS up here, HTML is the same.
(function () {
var $menu = document.getElementById('searchselectors'),
items = $menu.getElementsByClassName('item'),
$selectedItem = $menu.getElementsByClassName('selected')[0],
selectedIndex = Array.prototype.indexOf.call($selectedItem, items)+1;
document.body.addEventListener('keydown', function (e) {
switch(e.keyCode) {
case 40: // down arrow
$selectedItem.className = $selectedItem.className.replace(' selected','');
selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : selectedIndex;
$selectedItem = items[selectedIndex];
$selectedItem.className += ' selected';
break;
case 38: // up arrow
$selectedItem.className = $selectedItem.className.replace(' selected','');
selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : selectedIndex;
$selectedItem = items[selectedIndex];
$selectedItem.className += ' selected';
break;
}
}, false);
}());
Easiest way to get all the list items with class "item" is:
var items = $('.item');
for (var i = 0; i < items.length; i++) {
var item = items[i]; // iterate
}
And then, you can select the next item from the list
OR
you can do this
if (!$().next) {
var nextUL= $().parent.find('ul')
iterateThruList(nextUL);
}
You could use something like
var UL = $(".searchselectors").children().length; //number of UL (group names)
to iterate through items.

Categories