Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constantly Moving A Button Back And Forth In Vanilla JS

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading