Creating a tab component using vanilla javascript

I am facing an issue with my tab component in plain JavaScript. The content displays correctly in debug mode, but after compilation, it does not show up on the browser. Additionally, when I select a tab, the 'activeNav' class is applied to indicate the active state, but it disappears once the page fully loads. Can someone help me identify what I may be doing wrong?

function selectTab(evnt, targetBlock) {
  var i;
  var elementList = document.getElementsByClassName("displayContent");

  for (i = 0; i < elementList.length; i++) {
    if (elementList[i].id === targetBlock) {
      elementList[i].style.display = "inherit";
    }
  }

  evnt.currentTarget.classList.add("activeNav");
}
.displayContent {
  display: none;
  border: 1px solid #efefef;
  background-color: pink;
}

.active {
  display: inherit;
}

.activeNav {
  border: 1px solid red !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="nav nav-tabs">
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-1')">Tab title 1</a></li>
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-2')">Tab title 2</a></li>
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-3')">Tab title 3</a></li>
</ul>
<div id="Tabtitle-1" class="displayContent">
  <p>Content Block 1</p>
</div>
<div id="Tabtitle-2" class="displayContent">
  <p>Content Block 2</p>
</div>
<div id="Tabtitle-3" class="displayContent">
  <p>Content Block 3</p>
</div>

Answer №1

The anchor tag is causing the page to reload.

To stop the page from reloading, you need to use event.preventDefault().

function selectTab(evnt, targetBlock) {
  evnt.preventDefault();
  var i;
  var elementList=document.getElementsByClassName("displayContent");

  for(i = 0; i < elementList.length; i++) {
    if (elementList[i].id === targetBlock) {
      elementList[i].style.display = "inherit";
    }
  }

  evnt.currentTarget.classList.add("activeNav");
}
.displayContent {
  display: none;
  border: 1px solid #efefef;
  background-color: pink;
}
.active {
  display: inherit;
}
.activeNav {
  border: 1px solid red !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="nav nav-tabs">
<li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-1')">Tab title 1</a></li>
<li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-2')">Tab title 2</a></li>
<li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-3')">Tab title 3</a></li>
</ul>
<div id="Tabtitle-1" class="displayContent">
<p>Content Block 1</p>
</div>
<div id="Tabtitle-2" class="displayContent">
<p>Content Block 2</p>
</div>
<div id="Tabtitle-3" class="displayContent">
<p>Content Block 3</p>
</div>

Answer №2

So, when you click on an Anchor tag, it triggers the default behavior of refreshing and navigating to a new page.

To prevent this default action, you can use the following JavaScript function:

function showTab(event, target) {
  event.preventDefault();
  var j;
  var elements = document.getElementsByClassName("showContent");

  for(j = 0; j < elements.length; j++) {
    if (elements[j].id === target) {
      elements[j].style.display = "block";
    }
  }

  event.currentTarget.classList.add("activeLink");
}

Answer №3

To hide other tabs in an "else" condition, you must set display:none and remove the activeNav class from them using a for loop.

In addition, you can use evnt.preventDefault() in JavaScript or javascript:void(0) in the <a> tags' href to prevent the page from reloading.

Code Example:

function selectTab(evnt, targetBlock) {
  var i;
  var elementList = document.getElementsByClassName("displayContent");
  var anchorList = document.querySelectorAll(".a");
  for (i = 0; i < elementList.length; i++) {
    evnt.preventDefault();
    anchorList[i].classList.remove("activeNav");
    if (elementList[i].id === targetBlock) {
      elementList[i].style.display = "block";
    } else {
      elementList[i].style.display = "none";
    }
  }
  evnt.currentTarget.classList.add("activeNav");
}
.displayContent {
  display: none;
  border: 1px solid #efefef;
  background-color: pink;
}

.activeNav {
  border: 1px solid red !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="nav nav-tabs">
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-1')">Tab title 1</a></li>
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-2')">Tab title 2</a></li>
  <li><a class="a" href="" onclick="selectTab(event, 'Tabtitle-3')">Tab title 3</a></li>
</ul>
<div id="Tabtitle-1" class="displayContent">
  <p>Content Block 1</p>
</div>
<div id="Tabtitle-2" class="displayContent">
  <p>Content Block 2</p>
</div>
<div id="Tabtitle-3" class="displayContent">
  <p>Content Block 3</p>
</div>

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

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Display only a loading image with a see-through background after submitting the page

After submitting the page, I would like to display a loading image in the middle of the page with a transparent background. The current styling code I have used is as follows: #loading { position: fixed; top: 50%; left: 50%; z-index: 1104; ...

Discovering the right place to establish global data in Nuxt JS

Exploring the world of NuxtJS today, I found myself pondering the optimal method for setting and retrieving global data. For instance, how should a frequently used phone number be handled throughout a website? Would utilizing AsyncData be the most effecti ...

Troubleshooting Problems with Owl Carousel Loading

Having trouble with Owl Carousel loading issue. I've set up my carousel using the Owl Carousel jQuery plugin as guided, but it's showing me an "owl-carousel loading" class added to the DOM (owl-loading). I've tried adding custom styles and J ...

The Express middleware is not being utilized

There seems to be an issue with the middleware in the code below that is supposed to create a property req.user if req.session.user exists. Unfortunately, it appears that the middleware is not being triggered, causing 'hihihhiihi' to not be print ...

Learn how to utilize ajax and jquery to fetch data from an external database without the need for refreshing the page

I'm facing an issue with a small script. I want to query the Content in the database on a simple HTML page without any page refresh. <form method="get" name="formrrv" id="formrrv"> <input type="hidden" name="calculate" value="1 ...

Present the retrieved JSON data values in an alternative layout on the table

I am facing an issue with the data display in my current table setup. The data is fetched from an SQL server, encoded into JSON format, and the structure of the JSON output is causing a problem for me. You can see how it looks like here: The challenge I a ...

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

Expanding the outer div horizontally by using inner divs with scroll

Is there a way to ensure that all child divs are displayed on the same line within the outer div without wrapping to a second line? The width of the outer div should be fixed so that a scrollbar is visible, allowing us to scroll and view all inner divs. h ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

Using Python, Selenium, and Beautiful Soup to scrape LinkedIn data while being logged in and accessing user accounts

I have reached a point in my script where I am able to access a search page of profiles on LinkedIn. However, I am encountering difficulty in actually accessing these profiles. When attempting to view a profile, LinkedIn displays a message stating "You d ...

Inject JSON data into a JavaScript array

I am dealing with a JSON file in the following format: [{"excursionDay":"2"},{"excursionDay":"3"},{"excursionDay":"4"}] My goal is to extract the values of excursionDay and store them in an array in JavaScript like this: dayValues = [2,3,4] Here is m ...

Unexpected disconnection from Socket.io server

Utilizing node.js service and angular client with socket.io for extended duration http requests. Service: export const socketArray: SocketIO.Socket[] = []; export let socketMapping: {[socketId: string]: number} = {}; const socketRegister: hapi.Plugin< ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

What are the steps to ensure availability validation with jQuery validation?

I need assistance with validating post availability in the database using jQuery validation functionality. I have already implemented validation using the code below, but I am unsure where to place an Ajax validation before submitting the form. $(document ...

Modifying the Header Background Color

Looking for help on my forum at The header background on my site needs fixing. I am trying to change the entire header background to match the color of the logo background, but I'm unsure what codes need to be adjusted. Can anyone provide guidance? ...

Warning: Non-power of two image detected in Three.js

Encountering an issue with a warning in three.js that says: THREE.WebGLRenderer: image is not power of two (600x480). Resized to 512x512. Attempted to resolve it by adding THREE.LinearFilter, but no luck. var texture = new THREE.TextureLoader().load(data[ ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

Having trouble retrieving values for jVectorMap? The getElementById method doesn't seem to be functioning as

I have been trying to set markers on a jVectormap. I retrieve the content from my database and store it in a hidden input field. The format of the data is as follows: {latLng:[52.5200066,13.404954],name:'Berlin'},{latLng:[53.0792962,8.8016937],n ...