The goal is to move a button from one div
to another on click and then back to the other if clicked again and continue to do so each time it is clicked.
My problem is that the code I shared only runs once; what I need is for this behavior to run continuously.
const ham = document.getElementById('ham');
const mh = document.querySelector('.mobile-header');
const hc = document.querySelector('.header .content');
ham.addEventListener('click', function() {
document.body.classList.toggle('nav-is-toggled');
mh.insertAdjacentElement('afterbegin', ham);
ham.addEventListener('click', function() {
hc.insertAdjacentElement('afterbegin', ham);
});
});
<header>
<div >
<span id="ham">X</span>
</div>
</header>
<nav>
<div ></div>
</nav>
CodePudding user response:
You are adding a class to body, but there is no if-statement. See this example:
const ham = document.getElementById('ham');
const mh = document.querySelector('.mobile-header');
ham.addEventListener('click', function() {
document.body.classList.toggle('nav-is-toggled');
if (document.body.classList.contains('nav-is-toggled')) {
mh.insertAdjacentElement('afterbegin', ham);
} else {
mh.insertAdjacentElement('afterend', ham);
}
});
<div >mobile-header</div>
<div id="ham">ham</div>
CodePudding user response:
The simpliest way :
const
ham = document.getElementById('ham')
, mh = document.querySelector('.mobile-header')
, hc = document.querySelector('.header.content')
;
ham.onclick = () =>
{
let DomObj = document.body.classList.toggle('nav-is-toggled') ? mh : hc
DomObj.insertAdjacentElement('afterbegin', ham)
}
header, nav {
height : 3em;
background : lightsteelblue;
margin : 1em;
}
<header>
<div >
<span id="ham">XxxxxxxxxX</span>
</div>
</header>
<nav>
<div ></div>
</nav>
CodePudding user response:
You can use two divs, and add js. make two buttons, one in each div.
div2.style.display = block
let button1 = //select the button inside the 1st div
let div1 = //select the 1st div
let button2 = //…
let div2 = /…
button1.addEventListener(`click`, function(){div1.style.display = `none`
div2.style.display = block
})
button2.addEventListener(`click`, function(){div2.style.display = `none`
div1.style.display = block
})