How to change add and remove active class in JavaScript - javascript

I have navigation Bar where I want to add active class and remove it from a previous clicked list I think it's a basic thing but I'm new in javascript so i couldn't figure out the solution. I have code that works but the last and first list does not remove.
HTML CODE
<div id="icon-layout">
<ul>
<li>CLOTHING</li>
<li>BAGS</li>
<li>SHOES</li>
<li>ACCESSORIES</li>
<li>BEAUTY</li>
<li>ABOUT US</li>
<li>SERVICE</li>
</ul>
</div>
CSS
#icon-layout .active{
background-color: #FF4136;
color: white;
}
JAVASCRIPT
var activeclass = document.querySelectorAll('#icon-layout li');
for (var i = 0; i < activeclass.length; i++) {
activeclass[i].addEventListener('click', activateClass);
}
function activateClass(e) {
var previous = e.target.previousElementSibling;
var next = e.target.nextElementSibling;
e.target.classList.add('active');
previous.classList.remove('active');
next.classList.remove('active');
}

var activeclass = document.querySelectorAll('#icon-layout li');
for (var i = 0; i < activeclass.length; i++) {
activeclass[i].addEventListener('click', activateClass);
}
function activateClass(e) {
for (var i = 0; i < activeclass.length; i++) {
activeclass[i].classList.remove('active');
}
e.target.classList.add('active');
}
You may loop through all elements and remove class before adding one

Try using JQuery as it would definitely make your task easier:
$('#icon-layout li').on('click', function() {
$('.icon-layout li.active').removeClass('active');
$(this).addClass('active');
});

Related

How can I move a list item to the top on click?

If I click on a specific list item then it will goes to up in the list.
For example if i click on Price list it show above of the color list.
function setOnTop() {
var listItems = document.querySelector("li");
for (var i = 0; i < listItems.length; i++) {
listItems[$i].addEventListener("click", function() {
//Move on top
});
}
}
<ul>
<li>Color</li>
<li>Size</li>
<li>Price</li>
</ul>
const ul = document.querySelector("ul");
const li = ul.querySelectorAll("li");
function setTop() {
ul.prepend(this);
}
li.forEach((el) => {
el.addEventListener("click", setTop);
});
<ul>
<li>Color</li>
<li>Size</li>
<li>Price</li>
</ul>

Calling a function in mylibray onclick passing this

I've got this onclick call that works.
<ul id="ul_name" onclick="javascript:mylibrary.ul_action(this);">
I don't want to manually add the call on every ul so i tried this one:
window.onload = function() {
var u = document.querySelectorAll(".myclass ul");
var i;
for (i = 0; i < u.length; i++) {
u[i].onclick = mylibrary.ul_action(this);
};
};
But it doesn't work. It's this's scope wrong? Or what? Thank you.
You are calling the function immediately and assigning the return value as your click event handler.
You need to create a new function that calls your existing function with the argument you want (which isn't this because you want it to be the element):
window.onload = function() {
var mylibrary = {
ul_action: function(ul) {
console.log(ul.innerText);
}
};
var u = document.querySelectorAll(".myclass ul");
var i;
for (i = 0; i < u.length; i++) {
u[i].onclick = mylibrary.ul_action.bind(window, u[i]);
};
};
<main class="myclass">
<ul>
<li>One</li>
</ul>
<ul>
<li>Two</li>
</ul>
</main>

<ul> <li> list items adding onclick

I'm trying to add onclick to my list items and get the href with pure JavaScript.
I had it working from just a div but as soon as I added list items I was unable to get it to work.
var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");
var navBarList = navBarDiv.getElementsByTagName("ul");
// Attach click listeners for each of the nav links.
for (var i = 0; i < navBarList.length; i++) {
var navBarItems = navBarList[i].getElementsByTagName("li");
for (var j = 0; j < navBarItems.length; j++) {
navBarItems[j].addEventListener('click', function (e) {
e.preventDefault();
var pageURL = this.attributes['href'].value;
GetFileDoc(pageURL, function (doc) {
contentDiv.innerHTML = doc.getElementById("content").innerHTML;
});
});
}
}
<div id="navbar">
<ul>
<li>Homepage</li>
<li>About Us</li>
<li>Gallery</li>
<li>Contact Us</li>
</ul>
</div>
This appears to be the problem:
var pageURL = this.attributes['href'].value;
You're adding the click handler to the li element, not the a element. So there is no href attribute. I imagine there are two options:
Drill into the element further to get the href of the child a element, or
Add the click handler to the a element instead
For the first option, you might do something like this instead:
var pageURL = this.getElementsByTagName("a")[0].attributes['href'].value;
You'd want to put in some error checking of course, unless you're very confident that there will always be that first a element that you want.
For the second option, you might just modify what you're looping over. Perhaps something like this:
var navBarItems = navBarList[i].getElementsByTagName("a");
Assuming there are no other a elements in the hierarchy that you don't want to use for this.
Try with
a tag is the children of li so you need use querySelectorfor target the child element
And simply use with element.href for getting href value
var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");
var navBarList = navBarDiv.getElementsByTagName("ul");
for (var i = 0; i < navBarList.length; i++) {
var navBarItems = navBarList[i].getElementsByTagName("li");
for (var j = 0; j < navBarItems.length; j++) {
navBarItems[j].addEventListener('click', function(e) {
e.preventDefault();
var pageURL = this.querySelector('a').href;
console.log(pageURL)
//GetFileDoc(pageURL, function(doc) {
//contentDiv.innerHTML = doc.getElementById("content").innerHTML;
// });
});
}
}
<div id="navbar">
<ul>
<li>Homepage</li>
<li>About Us</li>
<li>Gallery</li>
<li>Contact Us</li>
</ul>
</div>
You are adding event to each li in the list. According to the rest of the code, espscialy the line this.attributes['href'].value you expect to have link element loaded. You can load all the link elements instead right away by using
navBarList[i].querySelectorAll("a");
which gives you all the inner links.
Try this one:
var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");
var navBarLinks = navBarDiv.getElementsByTagName("a");
// Attach click listeners for each of the nav links.
for (var i = 0; i < navBarLinks.length; i++) {
navBarLinks[i].addEventListener('click', function (e) {
e.preventDefault();
var pageURL = this.attributes['href'].value;
GetFileDoc(pageURL, function (doc) {
contentDiv.innerHTML = doc.getElementById("content").innerHTML;
});
});
}
}
It's nearly the same except I filter directly to the anchor-tags and then there is a href attribute.
Without using ES6
Array.prototype.slice.call(document.querySelectorAll('#navbar ul li a')).map(function(item) {
item.addEventListener('click', function(e) {
e.preventDefault();
console.log("href", e.target.href);
});
});
<div id="navbar">
<ul>
<li>Homepage</li>
<li>About Us</li>
<li>Gallery</li>
<li>Contact Us</li>
</ul>
</div>
Using ES6
[...document.querySelectorAll('#navbar ul li a')]
.map((item) => {
item.addEventListener('click', (e) => {
e.preventDefault();
console.log("href", e.target.href);
});
});
<div id="navbar">
<ul>
<li>Homepage</li>
<li>About Us</li>
<li>Gallery</li>
<li>Contact Us</li>
</ul>
</div>
jQuery
jQuery('#navbar ul li').click(function() {
console.log("href", $(this).attr('href'))
});
Please try this code
var navBarDiv = document.getElementById("navbar");
var contentDiv = document.getElementById("content");
var navBarList = navBarDiv.getElementsByTagName("ul");
// Attach click listeners for each of the nav links.
for (var i = 0; i < navBarList.length; i++) {
var navBarItems = navBarList[i].getElementsByTagName("li");
for (var j = 0; j < navBarItems.length; j++) {
navBarItems[j].addEventListener('click', function (e) {
e.preventDefault();
var pageURL = this.getElementsByTagName('a')[0].href;
alert(pageURL);
GetFileDoc(pageURL, function (doc) {
contentDiv.innerHTML = doc.getElementById("content").innerHTML;
});
});
}
}

how to apply a java script array with an already orded list in html

Hi I was wondering if anyone could help me out. I need to apply an array I created in Java Script on the HTML page that already has the order list created.I keep on getting error messages that say "Cannot read property of 'inner.HTML' undefined.
Any help would be greatly appreciated:)
thanks!
Here is my code:
< div id = "results" >
< ul >
< li id = "1-1" > < /li>
<li id="1-2"></li >
< li id = "1-3" > < /li>
<li id="1-4"></li >
< li id = "1-5" > < /li>
</ul >
< /div>
</article >
< script >
//declared global variable with an array of variables.
var places = ["Switzerland", "Canada", "Australia", "Norway", "New Zealand"]
// function to place the country's name in the
// li id.
function processPlaces() {
var locations = "";
for (var i = 0; i < places.length; i++) {
var listItem = i + 1;
var list = document.getElementById("1-" + listItem);
locations = list.getElementsByTagName("li");
locations[1].innerHTML += places[i];
}
}
//runs setUpPage () function when page loads.
if (window.addEventListener) {
window.addEventListener("load", processPlaces, false);
} else if (window.attachEvent) {
window.attachEvent("onload", processPlaces, false);
} < /script>
ids cannot start with a number, so preface them with l or some letter (you can see the change in the snippet).
HTML elements cannot have spaces immediately following <, so < div> will render as text, and < /div> will also render as text. Make sure to remove all the excessive spacing.
Further, when you access the element with getElementById that is the actual <li> element, and using getElementsByTagName inside of that element will find nothing because there are no children to the <li> elements. Instead of taking that approach, remove it and simply use the <li> element you already have from using getElementById. Once you make these changes, your code should run as intended.
//declared global variable with an array of variables.
var places = ["Switzerland", "Canada", "Australia", "Norway", "New Zealand"]
// function to place the country's name in the
// li id.
function processPlaces() {
var locations = "";
for (var i = 0; i < places.length; i++) {
var listItem = i + 1;
var list = document.getElementById("l1-" + listItem);
list.innerHTML = places[i];//directly access <li> element
//locations = list.getElementsByTagName("li");
//locations[1].innerHTML += places[i];
}
}
//runs setUpPage () function when page loads.
if (window.addEventListener) {
window.addEventListener("load", processPlaces, false);
} else if (window.attachEvent) {
window.attachEvent("onload", processPlaces, false);
}
<div id = "results">
<ul>
<li id = "l1-1"></li>
<li id = "l1-2"></li >
<li id = "l1-3"></li>
<li id = "l1-4"></li >
<li id = "l1-5"></li>
</ul >
</div>
If the array is ordered already, why not just append to the <ul>? First set and id on your unordered list <ul id="myList">
for (var i = places.length - 1; i >= 0; i--) {
$('#myList').after($('<li />', { 'text': places[i] }));
};
JSFiddle
Cleaned it up a bit.
You can't have spaces right after < in your html tags.
Also, you cant start IDs with numbers.
Edit: Too slow, Travis answer explains this much better :)
var places = ["Switzerland", "Canada", "Australia", "Norway", "New Zealand"];
function processPlaces() {
for (var i = 0; i < places.length; i++) {
document.getElementById('a-' + (i+1)).innerHTML = places[i];
}
}
if (window.addEventListener) {
window.addEventListener("load", processPlaces, false);
} else if (window.attachEvent) {
window.attachEvent("onload", processPlaces, false);
}
<div id="results">
<ul>
<li id="a-1"></li>
<li id="a-2"></li>
<li id="a-3"></li>
<li id="a-4"></li>
<li id="a-5"></li>
</ul>
</div>

Check which list element have been clicked

I'm trying to check which li have been clicked in the unordered list. only the first li seems to work becouse it will alert 0 but rest of the li wont respond with an alert. Nodelist should contain element 0,1,2. Raw javascript only.
HTML
<ul class="slideshow-buttons">
<li></li>
<li></li>
<li></li>
</ul>
Javasript
var $ = function (selector) {
return document.querySelector(selector);
};
var knappar = $('.slideshow-buttons').getElementsByTagName('li');
for (var i = 0; i < knappar.length; i++) {
var knapp = knappar[i];
knapp.onclick = knappTryck;
}
Problem seems to be inside knappTryck
function knappTryck(){
var childs = $('.slideshow-buttons').getElementsByTagName("li");
for (var c = 0; c < childs.length; i++) {
if (this == childs[c])
alert (c);
break;
}
}
the problem is here:
for (var c = 0; c < childs.length; i++) {
you use element c to parse the vector but you increment i. Replace c with i or the other way around
Also add braces to the if statement
Since you are using jQuery, make it 100% with jQuery :)
This will work :)
jQuery Code:
$(document).ready(function() {
$(".slideshow-buttons li").live("click", function() {
alert($(this).index());
});
});
You can use a closure.
for (var i = 0; i < knappar.length; i++) {
var knapp = knappar[i];
knapp.onclick = (function(i){
return function(){
console.log(i, this); // this is the li you clicked, and i is the index
}
})(i);
}

Categories