Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly.

I attempted to modify a template from w3schools by replacing it with my own classes/ids in the code. I expected a standard tab functionality but instead, both tabs display all content when clicked and then disappear until the page is refreshed.

I realize that my code may not be minimal, but I'm unsure of how much I can trim without losing important context. For reference, I tested this code on Firefox.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

@font-face {
  font-family: "Roboto" src: url("Roboto-Bold-webfont.woff") format("woff");
  font-style: normal;
  font-weight: 700;
}

@font-face {
  font-family: "Roboto" src: url("Roboto-Regular-webfont.woff") format("woff");
  font-style: normal;
  font-weight: 400;
}

body {
  width: 100%;
  font-family: "Roboto", sans-serif;
  font-size: 15px;
  line-height: 1.5em;
}

.page {
  display: flex;
  justify-content: space-around;
  margin-top: 50px;
}

.sidebar {
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  align-items: center;
  position: fixed;
  top: 100px;
  left: 50px;
  width: 400px;
  /* border: 1px solid red; */
}

.sidebar-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 400px;
}

.sidebar img {
  height: 200px;
}

.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 50px 0 0 400px;
  /* border: 1px solid red; */
}

.page-tab {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.tab {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
}

.sidebar-button,
.tab {
  margin: 10px;
  height: 45px;
  background-color: #D99023;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  color: #FFFFFF;
  font-family: "Roboto", sans-serif;
  font-weight: 700;
  font-size: 20px;
}

.sidebar-button:hover,
.tab:hover {
  background-color: #9C5400;
}

.sidebar-button a {
  text-decoration: none;
  color: #FFFFFF;
}

.page-tab button:active {
  background-color: #9C5400;
  color: #FFFFFF;
}

.gallery-container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  padding-top: 50px;
}

.gallery-container img {
  height: 350px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Frogcroaks</title>
  <link rel="stylesheet" href="master.css">
</head>

<body>
  <div class="page">
    <nav class="sidebar">
      <img src="images/logo.png" alt="">
      <button class="sidebar-button">
          <a href="home.html">Home</a>
        </button>

      <button class="sidebar-button">
          <a href="commissions.html">Commission</a>
        </button>

      <button class="sidebar-button">
          <a href="about.html">About & Contact</a>
        </button>
    </nav>

    <div class="content">
      <nav class="page-tab">
        <button class="tab" onclick="openGallery(event, 'character-design')">
            Character Design
          </button>

        <button class="tab" onclick="openGallery(event, 'illustration')">
            Illustration
          </button>

      </nav>

      <div id="character-design" class="gallery-container gallery">
        <img src="images/poufdesign1.png" alt="" class="gallery">
        <img src="images/poufdesign2.png" alt="" class="gallery">
        <img src="images/poufdesign3.png" alt="" class="gallery">
        <img src="images/fairy-ring.png" alt="" class="gallery">
        <img src="images/luminae.png" alt="" class="gallery">
        <img src="images/griffoy.png" alt="" class="gallery">
        <img src="images/pokemon.png" alt="" class="gallery">
      </div>

      <div id="illustration" class="gallery-container gallery" style="display=" none "">
        <img src="images/eloa-growth2.png" alt="" class="gallery">
        <img src="images/eloa-growth1.png" alt="" class="gallery">
        <img src="images/seviper-zangoose.png" alt="" class="gallery">
      </div>

    </div>

  </div>

  <script>
    function openGallery(evt, galleryName) {
      // Declare all variables
      var i, gallery, tab;

      gallery = document.getElementsByClassName("gallery");
      for (i = 0; i < gallery.length; i++) {
        gallery[i].style.display = "none";
      }

      tab = document.getElementsByClassName("tab");
      for (i = 0; i < tab.length; i++) {
        tab[i].className = tab[i].className.replace(" active", "");
      }

      document.getElementById(galleryName).style.display = "block";
      evt.currentTarget.className += " active";
    }
  </script>

</body>

</html>

Answer №1

It appears that there are several issues with the provided code snippet. To address these problems, I have created a revised solution that incorporates JavaScript in a separate file named script.js. This file is then linked to the HTML document using the script tag's src attribute. If you wish to keep the JavaScript code within the HTML document itself, you can simply replace the existing content inside the <script> tag with the code provided below.

"use strict";

const tabBtns = document.querySelectorAll(".tab-btn");
const tabs = document.querySelectorAll(".gallery");

tabBtns.forEach(function (btn, i) {
  btn.addEventListener("click", function () {
    if (tabs[i].classList.contains("hidden")) {
      tabs[i].classList.toggle("hidden");
      tabs[Math.abs(i - 1)].classList.toggle("hidden");
    }
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

@font-face {
  font-family: "Roboto", sans-serif;
  src: url("Roboto-Bold-webfont.woff") format("woff");
  font-style: normal;
  font-weight: 700;
}

... (CSS styles continue) ...

.hidden {
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="/script.js" defer></script>
    <link rel="stylesheet" href="/style.css">
    <title>Document</title>
</head>

<body>
    ... (HTML structure continues) ...
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').valu ...

How can I dynamically update the content of the right side of the side navbar by clicking on navbar links?

I have a side-navigation bar with content on the right side. How can I display specific content on the right side when clicking on a navigation link? For example, only show the name when clicking on the name link and only show the password field when click ...

JQuery button.click() handler executes without a user click

Currently, I am in the process of tidying up the code for my auction game. However, I have encountered an issue where my function is triggered immediately after endAuction() is called rather than waiting for the button click event. Unfortunately, I am no ...

Is it possible to merge string and span elements to create a unified element?

In my current project using React, I am dealing with an array of strings and JSX Elements. For instance, the array has items like: [<span class="name">JCrew0</span>, "edited this document"]. I am attempting to display thes ...

Running and halting multiple intervals in Javascript - a guide

Imagine a scenario where I am setting up 3 intervals with times of 500ms, 1s, and 1.5s. When I click on the button for the 500ms interval, I want to stop the other two intervals and only run the 500ms one. The same goes for clicking on the 1s or 1.5s butto ...

It seems that BeautifulSoup and Selenium are unable to locate the div or text elements on the website

I have been attempting to utilize BeautifulSoup or Selenium in order to retrieve the Head to Head text or its corresponding div element on betexplorer (link provided below), but my efforts have unfortunately proved to be unsuccessful. Despite being able to ...

Using useState in ReactJS does not allow setting state data

I am working with a react component that handles agreements. import React from "react"; import { AgreementInfo } from "../../../../models/shop"; import { MdClose } from "react-icons/md"; import moment from "moment"; ...

Ordering items in Angular Filter OrderBy is based on a specific string sequence, rather than following

As I iterate through a list of objects in an ng-repeat, I am facing the challenge of sorting them based on their 'approved' attribute. The possible values for 'approved' are 'APPROVED', 'DENIED', or 'PENDING&apo ...

Issues with the CSS animation not properly scaling

I'm currently working on an animation using CSS keyframes. Here is what I have: @keyframes experience { 0% { -webkit-transform: scale(0,0); transform: scale(0,0); -webkit-transform: translateY(40px); transform: translateY(40px); opac ...

Is it possible to prefetch library calls in Next.js in advance?

Recently, I started working with GeoChart using react-google-charts (https://github.com/RakanNimer/react-google-charts). However, I noticed that several scripts load after the entire process is completed. In my scenario, is loading towards the end. Is t ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

Is the CSS3 bar chart flipped?

I'm currently developing a responsive bar chart, and everything seems to be going smoothly except for one issue - when viewing it in full screen, the bars appear to be flipped upside down. It's quite puzzling as all other elements such as text an ...

What is the best approach to conceal elements from the main template in Meteor using a template event?

I have a main template along with two others that are displayed using Iron routing: <template name="main"> <div id="templateMain" name="templateMain"> <a href="nfnoscar">The Legend of NFN Oscar</a> <br/> <a h ...

conceal a component within a different container

Is there a way to hide or show an element within a container based on the hover state of another container? Here is an example of what I have tried so far: HTML5 <div class="left-menu-container"> <div class="left-menu-inner-container"> ...

I'm in need of assistance with Laravel 6 to implement a search functionality that can search for users by name, specialty, and country

Whenever I click the Search button, an error (Undefined nom) pops up. I am looking for someone who can help me troubleshoot and fix my code. Here is the code that needs correction: Controller: doctors.php <?php namespace App\Http\Cont ...

Running a script through the terminal using an electron js application, but the process necessitates the installation of node js

I am currently working on a project that involves running a script through the system terminal using my Electron.js application. However, I am facing an issue with new users who may not be technically proficient and do not have Node.js installed on their s ...

The useParams() function is returning undefined, even though the parameter does exist in the destination URL

I have a complete inventory of items called "Commandes" (PS: the app is in French), displayed in a table with a column for each row that should redirect me to another component showing more details about the selected row. To achieve this, I need to utilize ...

The error message "TypeError: Cannot read property 'map' of undefined when trying to set state as an array"

Encountering an error while trying to map the state for my posts:[] object: Error message: TypeError: this.state.posts.map is not a function While searching for a solution, I found something similar on this link, but unfortunately, it did not solve the ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

Eliminating duplicate data submissions with jQuery Ajax

Encountering an issue with my jQuery AJAX submission process. JavaScript: $('#myform').submit(function () { if (validateEvenInputs()) { $('#btnevent').attr('disabled', 'disabled'); function ...