Make current selections visible through Javascript - javascript

To summarise the code, I have buttons that display different tabs when pressed. Within the tabs, there are more buttons that change the color of some div elements and only one tab can be opened at a time. All this works as it should for the most part.
All buttons had been using focus but I wanted to replace it with javascript so that the selection will be retained when clicking on different elements. No tabs should be visible if the current opened tab button is pressed like it does when the code first runs.
I have had a few issues trying to get this to work properly. At the moment, the color buttons remain clicked. When tab toggles, the tab button loses selection and the tab div doesn't close when I click on the current selected tab's button.
https://jsfiddle.net/gkde169x/4/
<button class="tabButton" onclick="toggle_tab('tabOne');">Tab One</button>
<button class="tabButton" onclick="toggle_tab('tabTwo');">Tab Two</button>
<div id="tabOne" class="clickedTab" style="display: none;">
<br><br>
<div id="paletteOne">
<button class="paletteButton" style="background-color: blue"></button>
<button class="paletteButton" style="background-color: red;"></button>
<button class="paletteButton" style="background-color: yellow;"></button>
<button class="paletteButton" style="background-color: Green;"></button>
<button class="paletteButton" style="background-color: Orange;"></button>
<button class="paletteButton" style="background-color: white;"></button>
</div>
</div>
<div id="tabTwo" class="clickedTab" style="display: none;">
<br><br>
<div id="paletteTwo">
<button class="paletteButton" style="background-color: blue"></button>
<button class="paletteButton" style="background-color: red;"></button>
<button class="paletteButton" style="background-color: yellow;"></button>
<button class="paletteButton" style="background-color: Green;"></button>
<button class="paletteButton" style="background-color: Orange;"></button>
<button class="paletteButton" style="background-color: white;"></button>
</div>
</div>
<div id="change1"></div>
<div id="change2"></div>
<script type="text/javascript">
const divOne = document.getElementById('change1');
const divTwo = document.getElementById('change2');
document.querySelectorAll('#paletteOne button').forEach(function (el) {
el.addEventListener('click', function () {
divOne.style.backgroundColor = el.style.backgroundColor;
el.className = "paletteSelect";
});
});
document.querySelectorAll('#paletteTwo button').forEach(function (el) {
el.addEventListener('click', function () {
divTwo.style.backgroundColor = el.style.backgroundColor;
el.className = "paletteSelect";
});
});
function toggle_tab(id) {
const target = document.getElementById(id);
if (!target) {
return;
}
// Hide unselected tabs
const tabs = document.querySelectorAll('.clickedTab');
for (const tab of tabs) {
tab.style.display = 'none';
}
// Show current tab
target.style.display = 'block';
}
What's the best way to accommodate this in my code?

to unclick the color button I would do something like this, (with each click check for clicked buttons and unclick)
const pal = document.getElementById('paletteOne')
pal.addEventListener('click', function(e) {
document.querySelectorAll('#paletteOne button').forEach(function(el) {
el.className = "paletteButton"});
if(e.target.className==="paletteButton"){
divOne.style.backgroundColor = e.target.style.backgroundColor;
e.target.className = "paletteSelect";
}
});
to hide selected tab when clicked on
const tabs = document.querySelectorAll('.clickedTab');
for (const tab of tabs) {
if(tab!== target || target.style.display === 'block'){
tab.style.display = 'none';
}else{
target.style.display = 'block';}
}
obviously these things can be done differently, I'm just working off your code...

In your javascript
function toggle_tab(id) {
const target = document.getElementById(id);
if (!target) {
return;
}
const tabShown = document.querySelectorAll('.show')
tabShown.forEach((tab) => {
if(target != tab) tab.classList.remove('show')
})
target.classList.toggle('show');
}
Also in your CSS use classes. (You can create one class and give it to both of them since they have so many styles in common and use tabTwo and tabOne classes only for differences.)
.tabContainer {/*here use this class, give this to both tabs*/
position: absolute;
margin-top: 38px;
height: 100px;
width: 100px;
padding-left: 50px;
padding-bottom: 50px;
border-style: solid;
border-color: black;
background: white;
display:none;/*here*/
}
.tabTwo {/*here use class*/
margin-left: 20px;
}
.show{
display:block;
}

Related

Toggle show/hide functions between multiple divs

I have a page on my site which has 3 separate 'hidden' divs. Each with it's own 'show/hide' button.
Currently... each div and button set functions independently.
Therefore... if all divs are shown (open) at the same time, they stack according to their respective order.
Instead of that, I would rather restrict the function a bit, so that only div can be shown (open) at a time.
Example: If Div 1 is shown, and the user then clicks the Div 2 (or Dive 3) button, Div 1 (or which ever div is open at the time, will close.
I am not sure how to adjust my code to make that all work together. I have tried a few ideas, but they were all duds. So I posted a generic 'independent' version below.
function show_Div_1() {
var div1 = document.getElementById("Div_1");
if (div1.style.display === "none") {
div1.style.display = "block";
} else {
div1.style.display = "none";
}
}
function show_Div_2() {
var div2 = document.getElementById("Div_2");
if (div2.style.display === "none") {
div2.style.display = "block";
} else {
div2.style.display = "none";
}
}
function show_Div_3() {
var div3 = document.getElementById("Div_3");
if (div3.style.display === "none") {
div3.style.display = "block";
} else {
div3.style.display = "none";
}
}
.div {
width: 270px;
height: 30px;
padding-left: 10px;
}
<button type="button" onclick="show_Div_1()">Div 1 - Red</button>
<button type="button" onclick="show_Div_2()" style="margin-left: 4px">Div 2 - Blue</button>
<button type="button" onclick="show_Div_3()" style="margin-left: 4px">Div 3 - Green</button>
<div id="Div_1" class="div" style="background-color:red; display: none;"></div>
<div id="Div_2" class="div" style="background-color:blue; display: none;"></div>
<div id="Div_3" class="div" style="background-color:green; display: none;"></div>
I would suggest using data attributes for a toggle. Why? you can use CSS for them and you can use more than just a toggle - multiple "values".
Here in this example I do your "click" but also added a double click on the button for a third value. Try some clicks and double clicks!
A bit of overkill perhaps but more than just "toggle" for example you could use this to show "states" of things like a stoplight or any number of things.
Use the grid display and move them by just adding a data attribute value and double click it to get it to go (using css) to some grid-area:, things like that.
const hideValues = {
hide: "hidden",
show: "showme",
double: "dblclick"
};
function dblClickHander(event) {
const targetSelecor = event.target.dataset.target;
const target = document.querySelector(targetSelecor);
const action = target.dataset.hideme == hideValues.double ? hideValues.hide : hideValues.double;
const toggleTargets = document.querySelectorAll('.toggle-target');
toggleTargets.forEach(el => {
el.dataset.hideme = hideValues.hide;
});
target.dataset.hideme = action;
}
function toggleEventHandler(event) {
const targetSelecor = event.target.dataset.target;
const target = document.querySelector(targetSelecor);
const showHide = target.dataset.hideme == hideValues.hide ? hideValues.show : hideValues.hide;
const toggleTargets = document.querySelectorAll('.toggle-target');
toggleTargets.forEach(el => {
el.dataset.hideme = hideValues.hide;
});
target.dataset.hideme = showHide;
}
/* set up event handlers on the buttons */
const options = {
capture: true
};
/* we do this first to prevent the click from happening */
const toggleButtons = document.querySelectorAll('.toggle-button');
toggleButtons.forEach(el => {
el.addEventListener('dblclick', dblClickHander, options);
});
toggleButtons.forEach(el => {
el.addEventListener('click', toggleEventHandler, options)
});
.toggle-target {
width: 270px;
height: 30px;
padding-left: 10px;
}
.toggle-target[data-hideme="hidden"] {
display: none;
}
.toggle-target[data-hideme="showme"] {
display: block;
}
.toggle-target[data-hideme="dblclick"] {
display: block;
border: solid 2px green;
padding: 1rem;
opacity: 0.50;
}
.red-block {
background-color: red;
}
.blue-block {
background-color: blue;
}
.green-block {
background-color: green;
}
<button type="button" class="toggle-button" data-target=".red-block">Div 1 - Red</button>
<button type="button" class="toggle-button" data-target=".blue-block">Div 2 - Blue</button>
<button type="button" class="toggle-button" data-target=".green-block">Div 3 - Green</button>
<div class="toggle-target red-block" data-hideme="hidden">red</div>
<div class="toggle-target blue-block" data-hideme="hidden">blue</div>
<div class="toggle-target green-block" data-hideme="hidden">green</div>
This can be done in many ways. I think the best approach in your case could be
BUTTONS
<button type="button" onclick="show_div('Div_1')">Div 1 - Red</button>
<button type="button" onclick="show_div('Div_2')" style="margin-left: 4px">Div 2 - Blue</button>
<button type="button" onclick="show_div('Div_3')" style="margin-left: 4px">Div 3 - Green</button>
SCRIPT
function show_div(div_id) {
var thisDiv = document.querySelector('#'+div_id);
var thisState = thisDiv.style.display;
// close all in any cases
document.querySelectorAll('.div').forEach(function(el) {
el.style.display = "none";
});
// open this div only if it was closed
if (thisState == "none" ){
thisDiv.style.display = "block";
}
}

Show and hide different divs on clicks on different buttons [duplicate]

This question already has answers here:
Multiple show/hide divs with separate toggle
(5 answers)
Closed 8 months ago.
I am trying to show and hide different div's on click on different buttons. For example, when I click button "1", it shows the block with id="block-1". When I click on button "4", the block with id="block-4" shows and previous block #block-1 hides. I tried using different ID's because I don't know any other solution to show blocks with different content inside. Unfortunately, my current code doesn't work properly: it toggles the right class to show the div, but I can't hide the previous div or change the block once the button with number is clicked. On the default state, when the page is loaded, the first block (#block-1) should always be visible. Here's the link to codepen with the result: https://codepen.io/tomavl/pen/vYRLJVY
<div class="filter">
<button class="filter-btn active" id="1">1</button>
<button class="filter-btn" id="2">2</button>
<button class="filter-btn" id="3">3</button>
<button class="filter-btn" id="4">4</button>
</div>
<div class="block">
<div class="block-1 block-card active" id="block-1">Block 1</div>
<div class="block-2 block-card" id="block-2">Block 2</div>
<div class="block-3 block-card" id="block-3">Block 3</div>
<div class="block-4 block-card" id="block-4">Block 4</div>
</div>
background-color: red;
color: white;
}
.block-card {
display: none;
}
.block-card.active {
display: block;
}
var filterBtn = document.querySelectorAll(".filter-btn");
for (var i = 0; i < filterBtn.length; i++) {
filterBtn[i].onclick = function () {
if (this.classList) {
for (var j = 0; j < filterBtn.length; j++) {
filterBtn[j].classList.remove("active");
}
this.classList.add("active");
} else {
this.active += " " + active;
}
};
}
$("#2").on("click", function (e) {
e.stopImmediatePropagation();
if ($(this).hasClass("active")) {
$(".block-2").addClass("active");
} else {
$(".block-2").removeClass("active");
}
});
$("#3").on("click", function (e) {
e.stopImmediatePropagation();
if ($(this).hasClass("active")) {
$(".block-3").addClass("active");
} else {
$(".block-3").removeClass("active");
}
});
$("#4").on("click", function (e) {
e.stopImmediatePropagation();
if ($(this).hasClass("active")) {
$(".block-4").addClass("active");
} else {
$(".block-4").removeClass("active");
}
});
You can achieve what you need with much less code by using common classes to group content by behaviour. You can use data attributes where required to store custom metadata in an element.
In the following example all buttons use the same event handler. The differences come simply from the data attribute on the button used to change the selector. The code just removes the active class from all relevant elements before applying it to the target.
let $blocks = $('.block-card');
$('.filter-btn').on('click', e => {
let $btn = $(e.target).addClass('active');
$btn.siblings().removeClass('active');
let selector = $btn.data('target');
$blocks.removeClass('active').filter(selector).addClass('active');
});
body {
background-color: red;
color: white;
}
.block-card {
display: none;
}
.block-card.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="filter">
<button class="filter-btn active" data-target="#block-1">1</button>
<button class="filter-btn" data-target="#block-2">2</button>
<button class="filter-btn" data-target="#block-3">3</button>
<button class="filter-btn" data-target="#block-4">4</button>
</div>
<div class="block">
<div class="block-card active" id="block-1">Block 1</div>
<div class="block-card" id="block-2">Block 2</div>
<div class="block-card" id="block-3">Block 3</div>
<div class="block-card" id="block-4">Block 4</div>
</div>

Click button to toggle class of parent element - pure javascript

I have multiple divs on the page with the class 'item' – I'd like to include a button within the div that when clicked will toggle append/remove the class 'zoom' on the 'item' div…
<div class="item">
<button class="zoomer"></button>
</div>
I've found plenty of code examples that target an id element, but struggling to find a solution that works with multiples of the same class element on one page.
Many thanks in advance!
You can use querySelectorAll to get all of the buttons and then you can use forEach so you can target the element's item parent.
// Get all the buttons
let zoomer_button = document.querySelectorAll('.zoomer');
// Loop through the buttons.
// Arrow function allows to pass the element
zoomer_button.forEach(button => {
// Add an event listener for a click on the button.
button.addEventListener('click', function(e) {
// the e is the event, and then you check what the target is, which is the button.
// then you can toggle a 'zoom' class on the parent 'item'
e.target.parentNode.classList.toggle('zoom');
});
});
.item.zoom {
background-color: blue;
}
<div class="item">
<button class="zoomer">button</button>
</div>
<div class="item">
<button class="zoomer">button</button>
</div>
<div class="item">
<button class="zoomer">button</button>
</div>
<div class="item">
<button class="zoomer">button</button>
</div>
<div class="item">
<button class="zoomer">button</button>
</div>
If it's nested a layer deeper, you can use parentNode twice.
// Get all the buttons
let zoomer_button = document.querySelectorAll('.zoomer');
// Loop through the buttons.
// Arrow function allows to pass the element
zoomer_button.forEach(button => {
// Add an event listener for a click on the button.
button.addEventListener('click', function(e) {
// the e is the event, and then you check what the target is, which is the button.
// then you can toggle a 'zoom' class on the parent 'item'
e.target.parentNode.parentNode.classList.toggle('zoom');
});
});
.item.zoom {
background-color: blue;
}
<div class="item">
<div class="media">
<button class="zoomer">button</button>
</div>
</div>
<div class="item">
<div class="media">
<button class="zoomer">button</button>
</div>
</div>
<div class="item">
<div class="media">
<button class="zoomer">button</button>
</div>
</div>
<div class="item">
<div class="media">
<button class="zoomer">button</button>
</div>
</div>
You can use querySelectorAll and access each element with e.target
document.querySelectorAll('.item > .zoomer')
.forEach(elem => elem.addEventListener('click', e => {
e.target.classList.toggle('someClass')
}))
.someClass{
background:limegreen;
}
<div class="item">
<button class="zoomer">1</button>
</div>
<div class="item">
<button class="zoomer">2</button>
</div>
<div class="item">
<button class="zoomer">3</button>
</div>
<div class="item">
<button class="zoomer">4</button>
</div>
In the example below, are 7 <button>s that do various stuff -- details are commented in example.
// Render 7 <menu>/<button> combos
[...new Array(7)].forEach((item, index) => {
document.querySelector('main').insertAdjacentHTML('beforeend', `
<menu class="item${index}">
<button class="btn${index}">${index}</button>
</menu>`);
});
/*~~~~~~~~~~~~~~~~~~~~~~~.btn0*/
// Click <button> remove it's parent (which also removes the <button>)
document.querySelector('.btn0').onclick = function(e) {
this.parentElement.remove();
}
/*~~~~~~~~~~~~~~~~~~~~~~~.btn1*/
// Click <button> -- <button> is removed but it's contents is left behind
document.querySelector('.btn1').onclick = unWrap;
function unWrap(e) {
const clicked = e.target;
const parent = clicked.parentElement;
while (clicked.firstChild) {
parent.insertBefore(clicked.firstChild, clicked);
}
clicked.remove();
}
/*~~~~~~~~~~~~~~~~~~~~~.btn4-6*/
// Collect all tags with a class that starts with "btn"
const btns = document.querySelectorAll("[class^='btn']");
// Adding .target class to the last 2 <button>s
btns.forEach((btn, idx) => {
if (idx > 4) btn.classList.add('target')
});
/*~~~~~~~~~~~~~~~~~~~~~~~.btn2*/
// Target third <button> by index
/*
When <button> clicked, it's parent gets .hide class which is:
visibility:hidden which would normally hide the <button> as well, but
.btn2 has visibility explicitly set to visible
*/
btns[2].onclick = e => e.target.closest('menu').classList.toggle('hide');
/*~~~~~~~~~~~~~~~~~~~~~~~.btn3*/
/*
Everytime the <button> is clicked, a copy of itself is made and the
clones also have this ability as well
*/
btns[3].addEventListener('click', copySelf);
function copySelf(e) {
let dupe = e.target.cloneNode(true);
e.target.parentElement.append(dupe);
dupe.onclick = copySelf;
}
/*~~~~~~~~~~~~~~~~~~~~~.btn4-6*/
/*
The click event is bound to the parent/ancestor tag <section>
Any click to any <button> will trigger the event handler.
.btn4, .btn5, and .btn6 all react in a specific manner because
the event handler, delegateClick(e) is using flow control statements and
specific criteria.
*/
document.querySelector('main').onclick = delegateClick;
let armed = false;
function delegateClick(e) {
const clicked = e.target;
if (clicked.matches('button') && !armed) {
clicked.classList.add('armed');
armed = true;
return;
}
if (clicked.matches('.armed.target') && armed) {
clicked.parentElement.style.cssText = `font-size: 5rem; margin: 0`
clicked.replaceWith(`💥`);
return;
}
if (clicked.matches('.target') && armed) {
clicked.classList.add('armed');
return;
}
if (clicked.matches('.armed') && armed) {
clicked.classList.remove('armed');
armed = false;
}
}
menu {
outline: dashed red 1px;
}
.hide {
visibility: hidden;
}
.btn2 {
visibility: visible
}
.armed {
animation: warning 1s linear infinite;
}
#keyframes warning {
50% {
opacity: 0;
}
}
.target.armed {
background: red;
color: white;
}
button {
font: inherit;
cursor: pointer;
}
<main></main>

How to change background color of button while clicking on it

I have a input box which consists of many buttons. i want it to behave like when clicking on a button i want that button row's background to be changed and revert it when clicking on other button.
I tried many approach but nothing works.
Can anyone help me in this scenario?
Here is my code:
var buttons = document.querySelectorAll(".green");
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test') var yellowButton = document.querySelectorAll(".yellow")[0];
if (this.className == "green") {
if (yellowButton) yellowButton.className = "green";
this.className = "yellow";
}
}
}
Are you trying to do some sort of toggling like this?
function myFunc(btn) {
//get the current active button
var activeBtn = document.querySelector('button.active-btn');
if (activeBtn) {
activeBtn.classList.remove('active-btn'); //remove the .active-btn class
}
btn.classList.add('active-btn'); //add .active-btn class to the button clicked
}
.active-btn.green {
background-color: green;
}
.active-btn.yellow {
background-color: yellow;
}
.active-btn.red {
background-color: red;
}
.active-btn.blue {
background-color: blue;
}
button {
color: orange
}
<div>
<button type="button" class="red" onclick="myFunc(this)">Red</button>
<button type="button" class="blue" onclick="myFunc(this)">Blue</button>
<button type="button" class="green" onclick="myFunc(this)">Green</button>
<button type="button" class="yellow" onclick="myFunc(this)">Yellow</button>
</div>
You can also try adding a default "active-btn" class to the button you want and also adding a disable/enable effect like so:
function myFunc(btn) {
//remove .active-btn class if button is currently active
if (btn.className.indexOf('active-btn') !== -1) {
btn.classList.remove('active-btn');
} else {
//get the current active button
var activeBtn = document.querySelector('button.active-btn');
if (activeBtn) {
activeBtn.classList.remove('active-btn'); //remove the .active-btn class on currently active button
}
btn.classList.add('active-btn'); //add .active-btn class to the button clicked if not active
}
}
.active-btn.green {
background-color: green;
}
.active-btn.yellow {
background-color: yellow;
}
.active-btn.red {
background-color: red;
}
.active-btn.blue {
background-color: blue;
}
button {
color: orange
}
<div>
<button type="button" class="active-btn red" onclick="myFunc(this)">Red</button>
<button type="button" class="blue" onclick="myFunc(this)">Blue</button>
<button type="button" class="green" onclick="myFunc(this)">Green</button>
<button type="button" class="yellow" onclick="myFunc(this)">Yellow</button>
</div>

How to apply javascript to multiple button groups

I have css and js on a button group so that when you click a button from the group it shows as active, and when you click a different button, that button becomes active and the rest are cleared. I have to have 22 of these button groups (I only put 2 here for the sake of space) on my page, when I have just one the code works, but when I add the others everything comes crumbling down, can anyone help! How do use the script multiple times, where the script is applied to every group and doesn't intervene with the others.
function codeAddress() {
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
}
window.onload = codeAddress;
.btn {
background-color: white;
border: 3px solid #0099ff;
color: #0099ff;
cursor: pointer;
float: left;
padding: 10px 16px;
font-size: 18px;
}
.active,
.btn:hover {
background-color: #0099ff;
color: white;
border: 3px solid #0099ff;
cursor: pointer;
}
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
Here give this ago. I believe this is the intended response you expect when clicking button from different groups. Something like radio buttons. As already mentioned an ID can only represent one element not several. Use class instead. So i have changed your id to a class btn-group.
function codeAddress() {
const btnClick = function () {
this.parentNode.getElementsByClassName("active")[0].classList.remove("active");
this.classList.add("active");
};
document.querySelectorAll(".btn-group .btn").forEach(btn => btn.addEventListener('click', btnClick));
// This is the same as above just another way of doing it. use which ever you like
// var btns = document.querySelectorAll(".btn-group .btn");
// for (var i = 0; i < btns.length; i++) {
// btns[i].addEventListener("click", function () {
// this.parentNode.getElementsByClassName("active")[0].classList.remove("active");
// this.classList.add("active");
// });
// }
}
window.onload = codeAddress;
.btn {
background-color: white;
border: 3px solid #0099ff;
color: #0099ff;
cursor: pointer;
float: left;
padding: 10px 16px;
font-size: 18px;
}
.active,
.btn:hover {
background-color: #0099ff;
color: white;
border: 3px solid #0099ff;
cursor: pointer;
}
<div class="btn-group">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<br style="clear:both">
<div class="btn-group">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
Here the example what you need https://jsbin.com/bomegabiqo/1/edit?html,js,output
First of all, I want to say that you don't need to have two div with the same id
The second point is that you need to attach eventListener to the parent element, due to best-practice and performance optimization (you can read about it somewhere)
So here is updated version of HTML:
<div id="myGroupButtonsWrapper">
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<div id="myDIVV">
<button class="btn">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
</div>
And JavaScript:
function codeAddress() {
function myClickCallback(e) {
if (e.target.className === 'btn') {
var allButtons = document.querySelectorAll("#myGroupButtonsWrapper .btn");
allButtons.forEach((elem) => {
elem.className = elem.className.replace(" active", "");
});
e.target.className += ' active';
} else {
return;
}
}
var header = document.getElementById("myGroupButtonsWrapper");
header.addEventListener("click", myClickCallback);
}
window.onload = codeAddress;
It's not working because you have multiple IDs:
<div id="myDIV">...</div>
<div id="myDIV">...</div>
You can't do this - first, it's invalid HTML, and second, it'll do one of two things with the JS: cause an error, which you can see in the console, or it'll treat header as a NodeList, which is a collection of nodes that match the query selection, which means that it won't work. If you make them all have different IDs (e.g. div1, div2, div3, etc), it'll work if you modify your code to take multiple divs.
The other option is to make a class (e.g. myDIV) and modify your existing JavaScript code to use a class.
Instead of individual buttons, I would recommend using radio buttons for something like this. It already has functionality built in to group together for a selection similar to what you're going for. Then you just have to use built in commands to set the active button or check the values.
https://www.w3schools.com/jsref/prop_radio_checked.asp
https://www.w3schools.com/html/html_forms.asp
it is fairly simple to accomplish this using just 3 steps.
// First step is to create a onBtnClick handler function:
// The btn which was clicked can be accessed from event.target
// And then we can use the build in function classList.toggle to toggle the active class on that btn
const onBtnClickHandler = function (ev){ev.target.classList.toggle("active")};
// Next step is to find all btns, this can be done using the build in querySelectorAll function
const btns = document.querySelectorAll('.btn'); //returns NodeList array
// Last step is to add the eventListener callback function to each btn
btns.forEach(btn => btn.addEventListener('click', onBtnClickHandler));
Hope this helps.

Categories

Resources