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 class="header content">
<span id="ham">X</span>
</div>
</header>
<nav>
<div class="mobile-header"></div>
</nav>
>Solution :
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 class="mobile-header">mobile-header</div>
<div id="ham">ham</div>