简体   繁体   中英

How do I toggle border between active icons on a nav bar?

I am a newbie working on a project and making a mock up of a budgeting website. There is a left side nav bar with three icons: home page, transactions, profile.

Following is my expected icon performance:

  1. When the page loads, screen should show a narrow blue border on the left of the home page icon.
  2. When you click the transactions icon, the blue border disappears from home page icon and appears next to the transactions icon.
  3. When you click on the transactions icon, a new page also comes up without using link. It has to be hidden or adjacent html.

Any pointers are helpful, but keep in mind I am very green so looking for the simplest solution that I can wrap my head around. I'm so lost. here is what I have so far:

html:

<nav id="nav-bar">

  <img class="logo" src="assets/icons/elephant.svg" alt="elephant on a ball"/>

  <section class="nav-icons">
   <button class="dashboard-icon"><img class="icon-1" src="assets/icons/dashboard.svg" alt="clip board"/></buttom>
   <button class="transactions-icon"><img class="icon-2" src="assets/icons/transactions.svg" alt="wallet and card"/></button>
   <button class="profile-icon"><img class="icon-3" src="assets/icons/profile.svg" alt="outline of head"/></button>
  </section>
</nav>

css:

.icon-border-left {
   border-left: 3px solid #1CA3BA;
}

js:

var dashboardIcon = document.querySelector('.dashboard-icon');
var transactionsIcon = document.querySelector('.transactions-icon');
var profileIcon = document.querySelector('.profile-icon');


transactionsIcon.addEventListener('click', addBlueBorder)

function addBlueBorder() {
  transactionsIcon.classList.add('icon-border-left');
};

You can adjust you javascript slightly better. Instead of considering clicks on individual icons, consider them on the whole. To make it as simple as possible you can use jQuery. You remove the class from every icon and then add the class to the icon that was clicked.

$(".nav-icons>button").on("click",function(){
  $(".nav-icons>button").removeClass("icon-border-left");
  $(this).addClass("icon-border-left");
}

In vanilla javascript, you would write something like this :

var icons = document.querySelectorAll(".nav-icons > button");

for (i = 0; i < icons.length; i++) {
  icons[i].addEventListener("click", function() {
    document.getElementsByClassName("icon-border-left")[0].classList.remove("icon-border-left");
    this.classList.add("icon-border-left");
  });
}

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