Move button when clicked - javascript

How do I move the button from the div with id of two to the div with id of one when I click the button?
<div id="one">
</div>
<div id="two">
<button onclick="moveMe"></button>
</div>
function moveMe() {
// ??
}

We can do this using removeChild and appendChild js features. Provided an example below with working code.
const one = document.getElementById("one");
const two = document.getElementById("two");
const allButtons = document.getElementsByTagName("button");
for(let i = 0; i < allButtons.length; i++) {
const btn = allButtons[i];
btn.addEventListener("click", function(e) {
const el = e.currentTarget;
const newParent = el.parentNode.id == "one" ? two : one;
el.parentNode.removeChild(el);
newParent.appendChild(el)
});
}
.section {
height: 100px;
width: 150px;
padding: 4px;
margin: 5px;
float: left;
}
#one {
background: #CCC;
}
#two {
background: #eee;
}
button {
margin: 2px;
padding: 4px;
}
<h3>Toggle button between container on click</h3>
<div>
<div class="section" id="one"></div>
<div class="section" id="two"> <button>Move me 1</button> <button>Move me 2</button></div>
</div>

function moveMe() {
const divTwo = document.getElementById("two")
const divOne = document.getElementById("one")
const newButton = document.createElement("button")
newButton.innerText = "Click me"
divOne.appendChild(newButton)
divTwo.children[1].remove()
}
<div id="one">
<p>
div one
</p>
</div>
<div id="two">
<p>
div two
</p>
<button onclick="moveMe()">Click me</button>
</div>

You can try this:
// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');
// add eventListener
button.addEventListener('click', moveButton);
// move the button
function moveButton() {
firstDiv.append(button);
}

<div id="one">
</div>
<div id="two">
<button id="btn" onclick="moveMe">MoveMe</button>
</div>
function moveMe() {
var divOne = document.querySelector("#one");
var btn = document.querySelector("#btn");
divOne.appendChild(btn);
}

You can use code below to move the element.
There's some changes that I made on your code,
you can use version 1 or version 2
the changes on first version is i add "id" attribute on the element so we don't resort to use the tag only as selector, of course you can also use #two>button to make it more precise
the changes on second version is i add a parameter to your function this time it will handle the current element using "this" keyword when calling the function
function moveMe(){
// one.appendChild(document.querySelector("button"));
one.appendChild(move);
}
function moveMeV2(element){
one.appendChild(element);
}
<div id="one">
<span>one</span>
</div>
<div id="two">
<span>two</span>
<button id="move" onclick="moveMe()">Move Me</button>
<button onclick="moveMeV2(this)">Move Me V2</button>
</div>

Related

Hide/Show div and then hide all div

I am trying to make a "meet the staff" section that has hidden bios that display on click. Right now the div displays as it should, but only disappears when the original button is clicked again. I am needing some additional javascript to hide any opened divs when a different (or same) button is clicked. I don't know enough javascript to know what to try in order to make this happen. Thanks in advance!
HTML
<div id="lastname" class="toggle-div" style="display: none;">
<div><p>bio</p>
</div>
</div>
<button class="bio-button" onclick="myBiof()">Click for Bio</button>
Javascript
<script>
function myBiof() {
var y = document.getElementById("lastname");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
</script>
You will need to add some attributes to your HTML to keep track of which item is active, what item a button controls and which ones should be hidden from screen readers. aria-controls aria-expanded and aria-hidden do just that. Once a button is clicked... if it is currently open, just close it (remove active) and toggle the appropriate attributes. If it is not open, close all of them (remove active), open the one you clicked on (add active) and toggle the appropriate attributes. Here is a simple example:
const buttons = document.querySelectorAll("button");
const people = document.querySelectorAll(".person");
const handleClick = (event) => {
const clickedBtn = event.target;
if (clickedBtn.getAttribute("aria-expanded") === "true") {
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.remove("active");
person.setAttribute("aria-hidden", "true");
clickedBtn.setAttribute("aria-expanded", "false");
} else if (clickedBtn.getAttribute("aria-expanded") === "false") {
people.forEach(person => {
person.classList.remove("active")
person.setAttribute("aria-hidden", "true");
});
buttons.forEach(button => button.setAttribute("aria-expanded", "false"));
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.add("active");
person.setAttribute("aria-hidden", "false");
clickedBtn.setAttribute("aria-expanded", "true");
}
}
buttons.forEach(button => button.addEventListener("click", handleClick));
button {
display: block;
background: transparent;
border: none;
border-bottom: 1px solid #000;
width: 100%;
height: 2rem;
}
.person-container {
width: 400px;
margin: 0 auto;
}
.person {
display: none;
border-left: 1px solid #000;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
padding: 1rem;
}
.person h2 {
margin-top: 0px;
}
.person p {
margin-bottom: 0px;
}
.active {
display: block;
}
<div class="person-container">
<button aria-controls="person-one" aria-expanded="false">Show Person One</button>
<div id="person-one" aria-hidden="true" class="person">
<h2>Name One</h2>
<p>Person One Bio</p>
</div>
<button aria-controls="person-two" aria-expanded="false">Show Person Two</button>
<div id="person-two" aria-hidden="true" class="person">
<h2>Name Two</h2>
<p>Person Two Bio</p>
</div>
<button aria-controls="person-three" aria-expanded="false">Show Person Three</button>
<div id="person-three" aria-hidden="true" class="person">
<h2>Name Three</h2>
<p>Person Three Bio</p>
</div>
</div>
/*
Function to add all the events to the buttons.
Checking if divs are hidden or not with [data-hidden] attribute.
This HMTML attributes can be named however you want but starting
with data-
Note that this code will only work if every button
is placed in the HTML after the bio div
*/
function addEventsAndListenToThem() {
const buttons = document.querySelectorAll('.bio-button')
buttons.forEach(btn => {
btn.onclick = (e) => {
const target = e.target.previousElementSibling
// If element is hided, show it changing
// attribute data-hidden value to false
target.getAttribute('data-hidden') === 'true' ?
target.setAttribute('data-hidden', 'false') :
target.setAttribute('data-hidden', 'true')
}
})
const hide_or_show_all = document.querySelector('.bio-button-all')
// Var to check wether .bio-button-all
// has been pressed or not
var showing = false
hide_or_show_all.onclick = () => {
// Get al divs with data-hidden property
const all_bios = document.querySelectorAll('div[data-hidden]')
showing === false ? (
() => {
// Show all divs
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'false'))
showing = true
}
)() :
(
// Hide all divs
() => {
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'true'))
showing = false
}
)()
}
}
addEventsAndListenToThem()
/*
Display none only to [data-hidden="true"] elements
*/
[data-hidden="true"] {
display: none;
}
.bio-button,
.bio-button-all {
display: block;
margin: 10px 0px;
}
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>First bio</p>
</div>
</div>
<button class="bio-button">Click for first Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Second bio</p>
</div>
</div>
<button class="bio-button">Click for second Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Third bio</p>
</div>
</div>
<button class="bio-button">Click for third Bio</button>
<button class="bio-button-all">Show/Hide all</button>

button toggle display show hide

I want to show-hide the display of these layers with a button click. I can't figure out how to do it with 2 buttons, and 2 divs...
Html:
<div id="first">This is the FIRST div</div>
<div id="second">This is the SECOND div</div>
<button id="toggle">Show first div and hide second div</button>
<button id="toggletoo">Show second div and hide first div</button>
Css:
#first {
display: none;
}
#second {
display: none;
}
Js:
const targetDiv = document.getElementById("first");
const btn = document.getElementById("toggle");
btn.onclick = function () {
if (targetDiv.style.display !== "none") {
targetDiv.style.display = "block";
} else {
targetDiv.style.display = "none";
}
}
https://codepen.io/MaaikeNij/pen/YzrgbQw
Try with the following code:
#first{
display: block; /* <--- change */
}
#second {
display: none;
}
const firstDiv = document.getElementById("first");
const secondDiv = document.getElementById("second");
document.getElementById("toggle").onclick = function () {
if (firstDiv.style.display === "none") {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
} else {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
}
}
There's lots of ways to do this. One common way I've seen in various templates is to add and remove classes. Another way is to call the function from the button's onclick attribute. But my favorite is to write a function that requires no editing of the div HTML because I don't want to interfere with the HTML guy's work, I just want to put functioning code in there. (BTW, I am positive there is a more elegant way to write this, but here ya go!)
const firstDiv = document.querySelector("#first");
const secondDiv = document.querySelector("#second");
const firstButt = document.querySelector("#toggle");
const secondButt = document.querySelector("#toggletoo");
firstButt.addEventListener("click",toggleDivShowHide);
secondButt.addEventListener("click",toggleDivShowHide);
function toggleDivShowHide() {
if (firstDiv.style.display !== "none") {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
} else {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
}
}
You're saying "if the first div is set to none, then set it to block and set the second div to none. Otherwise, do the opposite."
I tried something different, this is working :)))
<div id="first" style="display:none;"> This is the FIRST div</div>
<div id="second" style="display:none;"> This is the SECONDdiv</div>
<input type="button" name="answer" value="Show first div and hide second div" onclick="showDivOne()" />
<input type="button" name="answer" value="Show second div and hide first div" onclick="showDivTwo()" />
function showDivOne() {
document.getElementById('first').style.display = "block";
document.getElementById('second').style.display = "none";
}
function showDivTwo() {
document.getElementById('second').style.display = "block";
document.getElementById('first').style.display = "none";
}
https://codepen.io/MaaikeNij/pen/vYeMGyN
Correction: you should add event Listener for both toggle & toggletoo.
Solution: solution with reusable code.
const Toggles = document.querySelectorAll('.toggle');
const Hides = document.querySelectorAll('.hide');
Toggles.forEach((el) => {
el.addEventListener("click", (e) => {
Hides.forEach((el) => {
el.parentElement.firstElementChild.classList.add('hide');
});
e.target.parentElement.firstElementChild.classList.toggle('hide');
});
})
.hide {
display: none;
}
<div>
<div class="hide">This is the FIRST div</div>
<button class="toggle">Show first div and hide first div</button>
</div>
<div>
<div class="hide">This is the SECOND div</div>
<button class="toggle">Show second div and hide first div</button>
</div>
<div>
<div class="hide">This is the Third div</div>
<button class="toggle">Show Third div and hide first div</button>
</div>
<div>
<div class="hide">This is the Fourth div</div>
<button class="toggle">Show Fourth div and hide first div</button>
</div>
For precisely such cases, javascript has the toggle function. I rewrite your code a little bit.
const btns = document.querySelectorAll(".toggleBtn");
btns.forEach(b => {
b.onclick = function (e) {
reset();
console.log(e.target.getAttribute('data-target'))
const target = e.target.getAttribute('data-target');
const t = document.querySelector('#' + target);
t.classList.toggle('hide');
}
});
function reset() {
const divs = document.querySelectorAll('.out');
divs.forEach(d => d.classList.add('hide'))
}
.hide {
display: none;
}
<div id="first" class="out hide">This is the FIRST div</div>
<div id="second" class="out hide">This is the SECOND div</div>
<button class="toggleBtn" data-target="first">Show first div and hide second div</button>
<button class="toggleBtn" data-target="second">Show second div and hide first div</button>

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

How to separete div blocks with the same class but diffent features

Good day!
I have a pop-up section. There are 2 div blocks in it with identical structure. The idea is to have 2 buttons (one is to edit a profile the other is to create a new card with some info) that will call this pop-up, but i need to track which one is called. The popup itself has a darker background compare to main page and a form. I have thought of a modifier popup__container_type_(edit/create) that has a display: none command so when i toggle it it the popup would appear with the right form. Most likely my logic was mistaken. I dont know how to distiguish them (div blocks) correctly.
Another problem is that closebutton seems to work for one form only.
Any help would be great!
HTML:
<section class="popup">
<div class="popup__container popup__container_type_edit">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 1</h2>
<input type="text" class="popup-form__input popup-form__input_type_name" name="name">
<input type="text" class="popup-form__input popup-form__input_type_job" name="job">
<button type="submit" class="popup-form__savebutton">Save</button>
</form>
</div>
<div class="popup__container popup__container_type_create">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 2</h2>
<input type="text" class="popup-form__input popup-form__input_type_place" placeholder="Name of the place" name="place">
<input type="text" class="popup-form__input popup-form__input_type_imagelink" placeholder="Image link" name="imagelink">
<button type="submit" class="popup-form__savebutton">Create</button>
</form>
</div>
</section>
JS:
let popUpSection = document.querySelector(`.popup`);
let cancelButton = popUpSection.querySelector(`.popup__cancelbutton`);
let popUpContainer = popUpSection.querySelector(`.popup__container`);
let formElement = popUpSection.querySelector(`.popup-form`);
let newInputName = popUpSection.querySelector(`.popup-form__input_type_name`);
let newInputJob = popUpSection.querySelector(`.popup-form__input_type_job`);
let inputName = document.querySelector(`.profile-info__title`);
let inputJob = document.querySelector(`.profile-info__text`);
let editButton = document.querySelector(`.profile-info__editbutton`);
let createButton = document.querySelector(`.profile__addbutton`);
//Open / close popup section
let formTogglePopUp = () => {
if (!popUpSection.classList.contains(`popup_acitve`)){
//Autofill
newInputName.value = inputName.textContent;
newInputJob.value = inputJob.textContent;
}
popUpSection.classList.toggle(`popup_active`);
}
//Save input changes
function popUpFormSaved (event) {
event.preventDefault();
inputName.textContent = newInputName.value;
inputJob.textContent = newInputJob.value;
formTogglePopUp();
}
formElement.addEventListener('submit', popUpFormSaved);
cancelButton.addEventListener('click', formTogglePopUp);
editButton.addEventListener('click', formTogglePopUp);
createButton.addEventListener(`click`, formTogglePopUp);
CSS:
.popup__container
{
display: block; *by default*
}
.popup__container_type_(edit/create)
{
display: none;
}
.popup
{
display:none;
}
.popup__active
{
display: flex;
}
You can do it with js, set ids and use them instead of class, it's more easy.
function popUpEdit() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpEdit").style.display = "block";
}
function popUpCreate() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpCreate").style.display = "block";
}
#popUp, #popUpEdit, #popUpCreate {
display: none;
}
<div class="smt">
Hello
<button onclick="popUpEdit()">Edit</button>
</div>
<div class="smt">Hello
<button onclick="popUpCreate()">Create</button>
</div>
<section id="popUp">
<div>popUp</div>
<div id="popUpEdit">Edit-popup</div>
<div id="popUpCreate">Create-popup</div>
</section>
Generaly, I do that this way:
const SectionPopUp = document.querySelector('section.popup')
function show(elm)
{
SectionPopUp.classList.toggle('Create','Create'===elm)
SectionPopUp.classList.toggle('Edit','Edit'===elm)
}
section.popup,
section.popup.Edit > div:not(.popup__container_type_edit),
section.popup.Create > div:not(.popup__container_type_create) {
display:none;
}
section.popup.Edit,
section.popup.Create {
display:block;
}
/* cosmetic part, just for testing here */
section.popup > div {
border : 1px solid aqua;
padding : .6em;
margin : 1em;
width : 15em;
}
div.popup__container_type_create {
border-color: orange !important;
}
<button onclick="show('Edit')"> show Edit </button>
<button onclick="show('Create')"> show Create </button>
<button onclick="show('')"> show none </button>
<section class="popup">
<div class="popup__container popup__container_type_edit">
pop-up edit content
</div>
<div class="popup__container popup__container_type_create">
pop-up create content
</div>
</section>

How to add and remove a class to a div element plain javascript

I am trying to add different classes to a div based on what is clicked, which I've managed to do, but need to remove the previously clicked/selected class and replace with the clicked one, Can't seem to get the remove part right. Most of the solutions I've come across are either toggles or adding and removing between two classes, but not 3 or more.
Thanks
This is what I have tried so far and the add part works as expected but when I click a different button it does not remove the previous clicked one
The HTML
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
The Javascript
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
frame.classList.add(this.dataset.width)
if(frame.classList.contains(btns)){
frame.classList.remove(this.dataset.width)
}
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
Basically, what I am trying to do is a responsive frame which will adjust its width depending on what is clicked.
You can store the current class in a variable and use the remove() to remove the previous class on each click.
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
var currentClass;
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
if (currentClass) {
frame.classList.remove(currentClass);
}
currentClass = this.dataset.width;
frame.classList.add(currentClass);
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
Here's a generalized version to work with multiple elements. I've wrapped each frame and buttons in a section element. Then I've bound the event listeners to the sections and used event bubbling / event delegation to perform the switch. I've also used a data attribute on the target frame to hold the current state.
function setWidthClass(event) {
var newWidth = event.target.dataset.width;
//This identifies a button click with our dataset
if (newWidth) {
//get the target div
var target = this.querySelector(".frame");
//if the target has a class set remove it
if (target.dataset.width) {
target.classList.remove(target.dataset.width);
}
//Add the new class
target.classList.add(newWidth);
//Update the data on the target element
target.dataset.width = newWidth;
}
}
//Add the event listener
var sections = document.querySelectorAll(".varyWidth");
for (var i = 0; i < sections.length; i++) {
sections[i].addEventListener("click", setWidthClass);
}
.w-third {
color: red;
}
.w-half {
color: blue;
}
.w-full {
color: green;
}
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
Rather than track the current class, you can also just reset it:
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
// reset the classList
frame.classList = ["frame"];
frame.classList.add(this.dataset.width)
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>

Categories