简体   繁体   中英

Use a Click Event to Add and Remove a Class to individual loop items

I want to add a CSS class to a nav menu item each time it's clicked (so i can then style that menu item so people know this is the page they are on). I know I need to loop through the .menu-item class and add / remove a new CSS class using a loop, but I can't seem to get it to play ball.

I'm guessing I need to make the .menu-item the 'this' object and use a boolean to add or remove the CSS class, dependent on whether the currentItem variable is set to true or false.

I can't seem to get this to play though and I'm not 100% sure I'm using the event listener in the correct way.

Any help would be awesome.

codepen: https://codepen.io/emilychews/pen/eeKPoo?editors=1010

JS

var navlinks = document.getElementsByClassName('menu-item')
var currentItem = false;

 for (i = 0; i<navlinks.length; i+=1) {

    function addCurrentItemToMenu() {

    if (currentItem === false) {

        navlinks = this

        this.classList.add('current-item')
        currentItem = true

        } else {

            this.classList.remove('current-item')
            currentItem = false

        }
    }
}

navlinks.addEventListener("click", function(){
    addCurrentItemToMenu() 
}, false)

CSS

body, ul {padding: 0; margin: 0}

#main-header {width: 100%; height: 100px;}

#mobile-menu-button {display: none;}

#main-navigation {
  position: relative;
  width: 100%;
  height: 100px;
  background: red;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10px 5% 10px 5%;
  align-items: center;
}

ul#nav-menu-items {
  display: flex;
  margin-left: auto;
}

#main-navigation ul li {list-style-type: none;}

ul#nav-menu-items li a {
  padding: 10px 15px;
  margin: 0 5px;
  box-sizing: border-box;
  background: yellow;
  text-decoration: none;
  color:#000;
}

#main-navigation ul#nav-menu-items li a:hover {
  color:blue;
  transition: color .25s;
}

HTML

<header id="main-header">
  <nav id="main-navigation"> 
    <ul id="nav-menu-items">
      <li class="menu-item"><a href="https://www.google.com">News</a></li>
      <li class="menu-item"><a href="https://www.google.com">About</a></li>
      <li class="menu-item"><a href="https://www.google.com">Contact</a></li>
    </ul>  
  </nav>
</header>

Here is a modified codepen for your problem: https://codepen.io/anon/pen/RjJEWe?editors=1010 The code simply add current-item class to the clicked anchor, so you can style it however you want in css. You can also see event.preventDefault() in the code to prevent anchor from following your link, as it will reload the page and js won't do anything. It depends on the stack that you are using. If you have server backed website, the current link will be handled by the server and html returned will already have the class set appropriately, if you have frontend js framework (Angular, VueJS, ReactJS), you must handle it appropriately.

Just for your example you can see the code below:

var navlinks = document.querySelectorAll('li.menu-item > a');

// Loop through all the links and add event listener
navlinks.forEach(function(item) {
  item.addEventListener('click', function(event) {
    event.preventDefault();
    // Remove the class from all elements
    navlinks.forEach(function(item) {
      item.classList.remove('current-item');
    })
    // add the class to the current one
    this.classList.add('current-item');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM