I am attempting to implement tabbed content using JavaScript, but it seems to be functioning properly only on the initial

This is my HTML with CSS and JavaScript all in one place.

JavaScript


var links = document.getElementsByTagName("a"); //get the links 
var len = links.length;
for(var i = 0; i<len; i++) { 
    links[i].onclick = handleClick; // add onclick handler 
}

function handleClick(e){
    var target = e.target;
    var id = target.id + "content";
    document.getElementById(id).style.zIndex = 10;
}

HTML


<div id="tabbed">
<a href="#" id="tabe1">Tabe1</a>
    <div class="section" id="tabe1content">
            <div>
        <p> content1 </p>   
        </div>
    </div>
    <a href="#" id="tabe2">Tabe2</a>
    <div class="section" id="tabe2content">
            <div>
        <p> content2 </p>   
        </div>
    </div>
    <a href="#" id="tabe3">Tabe3</a>
    <div class="section" id="tabe3content">
            <div>
        <p> content3 </p>   
        </div>
    </div>
 </div>

CSS


.section{
    position:absolute;
    float:left;
    width:500px;
    background-color:gray;
    left:0;
    top:0;
    height:300px;
    margin-top:30px;
}
#tabbed{
    position:relative;

}
a {
    margin-right:10px;
    float:left;
    display:block;
}

After testing, I noticed that it only works once. When clicking on table 1 for the second time, it still shows table 3 instead. I'm looking for a solution to fix this issue. Is there a better way to achieve the desired functionality?

Answer №1

  • delegate event to parent element
  • keep track of the highest z-index value

Check out this JSFiddle link for more details.

.section{
    position:absolute;
    float:left;
    width:500px;
    background-color:gray;
    left:0;
    top:0;
    height:300px;
    margin-top:30px;
    z-index: 1;
}
#tabbed{
    position:relative;
}
a {
    margin-right:10px;
    float:left;
    display:block;
}

<div id="tabbed">
<a href="#" id="tabe1">Tabe1</a>
    <div class="section" id="tabe1content">
        <div>
            <p> content1 </p>   
        </div>
    </div>
    <a href="#" id="tabe2">Tabe2</a>
    <div class="section" id="tabe2content">
        <div>
            <p> content2 </p>   
        </div>
    </div>
    <a href="#" id="tabe3">Tabe3</a>
    <div class="section" id="tabe3content">
        <div>
            <p> content3 </p>   
        </div>
    </div>
 </div>

var root = document.getElementById("tabbed");
var veryTop = 2;

root.onclick = handleClick;

function handleClick(e){
    var target = e.target;
    if ( target.tagName !== 'A' ) { e.preventDefault(); return; }
    var tab = document.getElementById( target.id + 'content' );
    tab.style.zIndex = ( veryTop++ ).toString();
    e.preventDefault();
}

PS. This solution should address your issue with it only working once.

Answer №2

When you select a tab, towards the conclusion of your JavaScript code, you adjust the z-index value for each tab to 10. Once this adjustment is made, the z-index values do not revert back.

Within the onclick event handler, you must construct a string that reduces the z-index values for all other tabs; I am unsure of the exact method to accomplish this task, but your familiarity with the topic should enable you to successfully complete this portion.

Answer №3

To cycle through each item in your group named section, first, you need to reset the z-index for all elements before assigning a new value:

let elements = document.getElementsByClassName("section");
for (let j = 0; j < elements.length; j++) {
    elements[j].style.zIndex = 0; //or use your default value
}

let selectedElement = e.target;
let elementId = selectedElement.id + "content";
document.getElementById(elementId).style.zIndex = 10;

Answer №4

All of your z-index values are getting jumbled up together. To solve this, you can implement a simple sorting function:

function organizeZindex(){
   for(var x = 0; x<length; x++) { 
       var identifier = items[x].id + "container";
       document.getElementById(identifier).style.zIndex = 9;
    }
}

http://jsfiddle.net/AbCdE/

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

How to incorporate diagonal lines in CSS within its parent container?

Is there a way to create a diagonal line that fills in and fits perfectly into a box using just CSS, without the need for any background images? div.diagonal-container { border: 1px solid #000; width:400px; height:400px; margin: 0 auto; ...

What could be the reason why the call function does not function properly as a sorting mechanism?

Currently immersed in javascript the good parts, I stumbled across an interesting example by the author: ['d','c','b','a'].sort(function(a,b) { return a.localeCompare(b); }); The expected behavior was observed. I ...

Show a specific portion of an extremely large .svg image file using Angular.js directive with the help of javascript or css

Currently, I am facing a challenge with a large map image (3000x8000px) in .png format that I have converted to .svg for data visualization purposes. I am struggling to find a way to display a specific small section of this map.svg file on an HTML page u ...

I want to update the toggle switches within the GridToolbarColumnsButton component from MUI's DataGrid to checkboxes

Currently, I am developing a website where one of the pages has tabular data fetched from the backend. To filter this table, I utilized Mui filters from datagrid({...data}components={{ toolbar: CustomToolbar }}). Among these filters is a GridToolbarColumns ...

The command I gave is not being executed

I am attempting to replicate the functionality of nsClick with my custom directive by changing its priority. Here is my directive code: angular.module('MyApp').directive('nsClickHack', function () { return { restrict: 'E' ...

I wonder where this design is originating from

After exploring several of the suggested questions that appeared while typing, I was unable to find a solution to my issue. Currently, I am utilizing Uikit V2 and I have implemented a div with the Sticky component as shown below: <div class="uk-st ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

Javascript floating navigation toolbar

How can I create a minimalist launch bar with a search button that only appears on a page when a specific hotkey is pressed? I want to avoid using large libraries like mootools or FancyBox for this Chrome Extension project to keep it lightweight. Do you ...

Issue encountered while attempting to deactivate certain foundation CSS and JavaScript files

I am attempting to deactivate certain CSS files in the foundation framework, as they are unnecessary for my project. After installing foundation via a gem, I followed Ryan Bates' recommendation to modify the foundation_and_overrides.scss file by repl ...

Create a PDF document using pdfmake within an iframe element

I am using this JS code and would like to generate a PDF within an iframe tag using pdfmake library. function start(){ var docDefinition = { content: [ { table: { multiple pages headerRows: 1, widths: [ '*&apos ...

Experimenting with jQuery's .hide() and .show() functions with an alert message confirming that the div is not

Below is some simple code to demonstrate an issue: $('.myDiv').click(function() { $('.anotherDiv').hide(); alert('pause the ui'); $('.anotherDiv').show(); }); After clicking on the .myDiv element, the ...

Ways to align a group of rows in the center of a document

I'm struggling to center these rows in the middle of the page. Using a Bootstrap template, I've been customizing it to suit my webpage. https://i.sstatic.net/E9hHq.png I want the rows to be centered just like the text above them. Originally a che ...

Utilize both versions of Bootstrap seamlessly without causing any disruptions or issues

With a unique situation at hand, I find myself needing to display two different versions of Bootstrap on the same page. My Umbraco CMS relies on Bootstrap version 2.x by default, while my frontend pages utilize Bootstrap 4. However, certain Bootstrap 4 wid ...

Issue with GLTF Loader Trial: Encountering TypeError when trying to resolve module specifier "three". Invalid references detected; relative references must begin with either "/", "./", or "../"

I'm relatively new to working with three.js and I am currently attempting to load a model into my canvas. However, when I import the GLTFLoader, I encounter the error message mentioned in the console above. Despite checking the syntax and relative pat ...

A guide on transferring model value from a view to a controller upon button click in ASP.NET MVC

Is there a way to pass a value from a model in the view to a controller when a button is clicked, while also redirecting the user to that controller? Here is the code for the view: @model Status_Pedido.ViewModels.CodigoPedidoViewModel @{ ViewBag.Titl ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...

I am having trouble getting my CSS styles to apply to nested components within Bootstrap React components

Currently I am learning react and in the process of creating a website using react-bootstrap. While working on my navbar, I encountered an issue where I was unable to change the font and font-color of the navbar items. The CSS that I applied only affected ...

Utilizing the "onmouseover" event to show a tooltip with JavaScript

Is there a way to create small dialogue boxes using JavaScript for user guidance when entering data into a field by hovering over them? I am new to JavaScript and not sure if my approach is correct. Here is the code I have: <html> <head> ...

Utilizing a string as an argument in a function and dynamically assigning it as a key name in object.assign

Within my Angular 5 app written in TypeScript, I have a method in a service that requires two arguments: an event object and a string serving as the key for an object stored in the browser's web storage. This method is responsible for assigning a new ...