Toggles class function only works on first element - javascript

Hi guys I have written the following code in order to be able to toggle a class on and off an element on click.
The element:
<h4 class="swatch-label-size swatch__label--error">test</h4>
The functionality:
function newFunctionTest() {
var termsToggles = document.querySelectorAll('.swatch-label-size');
for (var i = 0; i < termsToggles.length; i++) {
termsToggles[i].addEventListener('click', toggleTerms);
}
}
function toggleTerms() {
var termsSection = document.querySelector('.swatch-label-size');
termsSection.classList.toggle('js-swatch-open');
}
I have three instances on the element with ".swatch-label-size" class in my DOM, but the function only works when I click the first one. Nothing happens on click of the second or third element. Have I not not bound my function to all instances of the class properly?

You are again getting the element inside the listener function toggleTerms so remove that and it works. Just click the text in the snippet below to get the effect of class being toggled. For simplicity, I have toggled the class that change the font color:
function newFunctionTest() {
var termsToggles = document.querySelectorAll('.swatch-label-size');
for (var i = 0; i < termsToggles.length; i++) {
termsToggles[i].addEventListener('click', toggleTerms);
}
}
function toggleTerms() {
this.classList.toggle('js-swatch-open');
}
//initialize listener
newFunctionTest();
.js-swatch-open{
color: red;
}
<h4 class="swatch-label-size swatch__label--error">test1</h4>
<h4 class="swatch-label-size swatch__label--error">test2</h4>
<h4 class="swatch-label-size swatch__label--error">test3</h4>

The termsSection in toggleTerms would always be the first matched element, you may consider to change it into this
function toggleTerms(event) {
var termsSection = event.target;
termsSection.classList.toggle('js-swatch-open');
}

Related

How to remove a class form from the previous and the next sibling label of the currently active label with javascript

I have a function to add a class civil-active to the label that is clicked. When the next label is clicked the class is added to it too, naturally. But I want the class civil-active to be there only on the clicked label and get it removed from its previous and next sibling if present.
the code that is adding the class is
js
var labels = document.getElementsByTagName("label");
for (let i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", addclass);
}
function addclass(event) {
event.target.classList.add("civil-active");
}
Please suggest me what should I do
In the event handler, find the element having the class and remove it.
function addclass(event) {
// Those lines will remove the class on the element that has it (if there is one)
let active = document.querySelector(".civil-active")
if(active){
active.classList.remove("civil-active");
}
event.target.classList.add("civil-active");
}

Change color of all elements in class on click JavaScript

I have an image (SVG) of a human body. I would like to use JavaScript so that when I click a particular area (say, the lower leg) then all of the elements with the class "lower-leg" (even if not clicked) have their color changed -- this makes it much easier for the user.
Here is the JavaScript I currently have:
function changeclassstyle() {
var c = document.getElementsByClassName("lower-leg");
for (var i=0; i<c.length; i++) {
c[i].style.fill = "red";
}
}
The problem with this code is that it is only generalized for "lower-leg". I may have over a dozen classes I would like this to work for and don't think it is efficient to write 12 functions with the only change being the class name. Is there a way to grab what class was selected and then input that in the function?
--
Additionally, I would love to figure out how, once that section of the body is selected, I can store the class name. I would, in the end, want to store the selection, along with other inputted information in a database. But, this may be for a future question unless someone can help!
Here's how I would do it (tested on a couple of div's).
What we're doing is passing the event object to the event handler (your changeclassstyle() function). It then uses the class of the clicked-on item (the event target's class) and changes everything else on that page with that same class name to use your new desired CSS style.
function changeclassstyle(e) {
// Get all items that have the same class as the item that was clicked
var limbs = document.getElementsByClassName(e.target.className); // for div's and the like
// var limbs = document.getElementsByClassName(e.target.className.baseVal); // turns out this is needed for SVG items
// "limbs" is an HTMLCollection, not an array, so functions like .foreach won't work; C-style for-loops or modern for/let/of loops are better
for (let item of limbs) {
item.style.backgroundColor = 'red';
// item.style.fill = 'red'; // This is probably what you need for your SVG items
}
// You could still use your C-style for loop if needed/wanted
/*
for (var i=0; i<limbs.length; i++) {
limbs[i].style.fill = "red";
}
*/
}
The onchange call looks like this (using my div as the example):
<div class="upper-arm" onclick="changeclassstyle(event)">
</div>
<div class="lower-leg" onclick="changeclassstyle(event)">
</div>
The whole example with simple div's.
<html>
<head><title>stuff</title></head>
<body>
<script type="text/javascript">
function changeclassstyle(e) {
// For debugging. You may want to expand 'e' here in your browser's debug tools if you're not seeing the values you need/want
console.log(e)
var limbs = document.getElementsByClassName(e.target.className.baseVal);
for (let item of limbs) {
item.style.backgroundColor = 'red';
}
}
</script>
<style type="text/css">
div {
height: 100px;
width: 100px;
background-color: 'white';
border: 1px solid black;
}
</style>
<div class="upper-arm" onclick="changeclassstyle(event)">
</div>
<div class="upper-arm" onclick="changeclassstyle(event)">
</div>
<div class="upper-arm" onclick="changeclassstyle(event)">
</div>
<div class="lower-leg" onclick="changeclassstyle(event)">
</div>
<div class="lower-leg" onclick="changeclassstyle(event)">
</div>
<div class="lower-leg" onclick="changeclassstyle(event)">
</div>
</body>
</html>
You can use parameters in function where you pass class and color like below
function changeStyle(cls,clr) {
let elems = document.getElementsByClassName(cls);
if(!elems) return;
for (let elem of elems) {
elem.style.color = clr;
}
}
As per the iteration of many classes like i said you can store classes in array and iterate each of them.
let classes = ['one','two','three','four'];
classes.forEach(function (cls) {
changeStyle(cls,"red");
});
You can play with fiddle here if you want to test/experiment: https://jsfiddle.net/thrL5uqw/8/
Note: Change style property as you wish, For now i have used color for demo
I'm a bit late to the party, but here's my take on the problem.
Like the others told you, you'll need to use an additional parameter to your function to specify the class you want to modify your elements (or try to figure out the class from the clicked element), therefore you should have something like that:
/**
* This function will handle the click event on one of the part of the SVG.
* #param {string} lClass This the class of the element to modify
*/
function handleClick(lClass) {
for (let e of document.getElementsByClassName(lClass)) {
// Here you can do all the changes you need on the SVG element.
e.style.fill = "red";
}
}
And when it comes to the event binding, you could do like the other suggested and add the onclick event binding propery on the HTML Element, or you could bind it in you JS with the addEventListener function (that way you don't have to repeat the onclick property on each of your SVG elements).
// For each element of all the listed class, bind the "click" event to the handleClick function
const listenClass = [/*List of your classes*/];
for (let l of listenClass) {
for (let e of document.getElementsByClassName(l)) {
e.addEventListener('click', handleClick.bind(this, l));
}
}
Demo: https://plnkr.co/edit/gay2yBaVi5QD868fsTa6?p=preview
I hope it helped.

Remove class from one element, while adding that class to another element using javascript

This question was quite hard to summarize in the title, but what I have is a group of elements with the class panel. When I click a panel, I add a class of open to it. What I also want to do is remove the open class if another panel already has the open class.
Here is the code:
const panels = document.querySelectorAll('.panel');
function toggleOpen() {
this.classList.toggle('open');
}
panels.forEach(panel => panel.addEventListener('click', toggleOpen));
Right now I can add the open class to however many panels I want, but I only want one panel to have the open class at a time.
Any help no how to achieve this?
The most efficient way is cache the DOM node is currently selected:
const panels = document.querySelectorAll('.panel');
let openedPanel = null;
function toggleOpen() {
if (openedPanel)
openedPanel.classList.remove('open');
this.classList.add('open');
openedPanel = this;
}
panels.forEach(panel => panel.addEventListener('click', toggleOpen));
As was mentioned, it would be more efficient also delegate the event, so if all the panels share some ancestor, you should add the event listener to that ancestor, and then from the event listener doing something like:
toggleOpen({target}) {
const panel = target.closest('.panel')
if (openedPanel)
openedPanel.classList.remove('open');
panel.classList.add('open');
openedPanel = panel;
}
But as said they need to share a common ancestor.
Because you only want one opened at a time. You can directly target that element by getting the elements with class open, targeting the first element and removing class open before you add it to the selected one.
let opened = document.getElementsByClassName('open')[0];
if(opened!=undefined)
opened.classList.toggle('open');
This way you dont have to loop or save an extra global variable.
const panels = document.querySelectorAll('.panel');
function toggleOpen() {
let opened = document.getElementsByClassName('open')[0];
if(opened!=undefined)
opened.classList.toggle('open');
this.classList.toggle('open');
}
panels.forEach(panel => panel.addEventListener('click', toggleOpen));
.panel {
width: 50px;
height: 50px;
margin: 1px;
background-color: aquamarine;
}
.open {
background-color: tomato;
}
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
var doc = document;
var panelButtons = doc.querySelectorAll(".panel");
for (var i = 0; i < panelButtons.length; i++) {
panelButtons[i].addEventListener("click", function (evt) {
clearBlueFromButtons();
evt.target.classList.add("blue");
});
}
function clearBlueFromButtons(){
for (var i = 0; i < panelButtons.length; i++) {
panelButtons[i].classList.remove("blue");
}
}
.blue{
background: blue;
}
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
<button class="panel">click me</button>
You can set the reference of the last opened panel in a variable and then remove the class name "open" when opening another panel, below an exemple:
// select all panels
const panels = document.querySelectorAll('.panel');
// define variable for the last clicked panel
let lastOpenedPanel;
/*
* Add the open class name for the current panel and remove it from the previous one
*/
function toggleOpen(
{
this.classList.toggle('open');
setLastOpenedTab(this);
}
/*
* Set the last opened tab and remove the open class from the previous one
*/
function setLastOpenedTab(context) {
if(lastOpenedPanel){
lastOpenedPanel.classList.remove('open');
}
lastOpenedPanel = context;
}
panels.forEach(panel => panel.addEventListener('click', toggleOpen))
I recommend the use of javascript module pattern to better organize and share your functions
I recommend also the use of Jsdoc to better add documentation to your javascript code
Note that the property "classList" is not supported by IE9:
https://www.w3schools.com/howto/howto_js_toggle_class.asp
Try adding these lines BEFORE “this.classList.toggle” in your toggleOpen function:
for (var i = 0; i < panels.length; i++){
panels[i].classList.remove(“active”);
}
Use an if statement to check if the element has "open" and "panel" then remove the open class. Below is the pseudo code:
if ((element.classList.contains(open)) == True && (element.classList.contains(panel))){
element.classList.remove("open");
}

How to remove the active class from all children in a parent using Javascript

I have created 3 div having the same class in a parent , and on the child element i am adding the active class and on click of second child adding the active class again but this time i want to remove the active state for first element.
How can i remove it in effective way?
Here is my code
<div class="tab-div">
<div class="tab">default</div>
<div class="tab" >hover</div>
<div class="tab">active</div>
</div>
Here is my javascript
var elements = document.querySelectorAll('.tab');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].onclick = function (event) {
console.log("ONCLICK");
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
You are not removing the active class from all elements when click event is triggered. So, what you can do is to loop over again to all the div and remove the active class on click event. I have created a custom function removeClass() that removes the active class on click event.
var elements = document.querySelectorAll('.tab');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].onclick = function (event) {
console.log("ONCLICK");
//remove all active class
removeClass();
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
function removeClass(){
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
}
}
.active{
color: green;
}
<div class="tab-div">
<div class="tab">default</div>
<div class="tab" >hover</div>
<div class="tab">active</div>
</div>
I suppose it depends how many divs you will ultimately have, and if only one div should be active at a time, but I think it would be more efficient to just find the active div and remove the class from that one rather than looping through all of them e.g.
var oldActiveElement = document.querySelector('.active');
oldActiveElement.classList.remove('active');
var newActiveElement = event.target;
newActiveElement.classList.add('active');
Since all of them have a class called tab, make sure you remove the class or property of active from all the classes by targeting the class tab and it would remove from all without doing any loop. Then add the property to the current one that is clicked.
$(".tab").click(function(){
$(".tab").removeClass('active');
$("this").addClass('active');
});
If the class is in the parent you can do sth like
$(".tab").click(function({
$(".tab").parent().removeClass('active');
$("this").parent().addClass('active');
});

Adding dynamic second class Jquery

I'm trying to add a second class to a group of buttons using a for loop in jQuery, with the second class set to the number of the current iterator(i). The first class for each button is assigned to "users". I want each button to have a dynamic second class so that when clicked, I can use its second class as an index to access a particular key in an object.
The problem I'm having is that each button has its second class set to 0. "users" is an array with length 4, so the buttons should have as their second class 0,1,2,3 in order.
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<button class="users '+ i +'"></button>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
$(".users").click(function() {
alert($(".users").attr('class').split());
// Alert returns "users 0" for each button.
});
});
The alert at the bottom is just a placeholder for now to check that the classes are set correctly. Thanks!
change code to below . change $(".users") to $(this) when you click on element.
$(".users").attr('class') always return all button element.
$(".users").click(function() {
alert($(this).attr('class').split());
});
When you use a getter method like .attr('class') on a set of elements, it will return the value of the first element in the set. when you say $('.users') it will return all elements with the class users.
In your case you want to have reference to the clicked button, which is available in the click handler as this so you can
$(document).ready(function() {
var users = ['u1', 'u2', 'u3']
for (var i = 0; i < users.length; i++) {
var $currentUser = $('<button class="users ' + i + '"></button>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
$(".users").click(function() {
alert(this.className.split(/\s+/));
alert(this.classList); //for ie 10+
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="userList"></div>

Categories