Guide on generating tabs with the power of Javascript and Jquery

Is it possible to create multiple tabs on a page using jquery or javascript, where clicking buttons on the menu slides in a new page without changing the URL? I already have the HTML and CSS prepared.

div.tabContent.hide {
  display: none;
}
nav {
  background: rgba(0, 0, 0, 0);
  height: 80px;
  border-radius: 0px;
}
nav ul {
  width: 50%;
  margin: auto;
}
nav ul li {
  list-style-type: none;
  width: 150px;
  margin-top: 15px;
  float: left;
  border: none;
  text-align: center;
}
li a {
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  text-decoration: none;
  color: #333333;
  border-radius: 0px;
  text-shadow: 0 1px 1px rgba(0, 0, 0, .5);
  line-height: 50px;
  display: block;
  transition: all ease-in-out 250ms;
}
li a:hover {
  background: rgba(255, 255, 255, .2);
  box-shadow: 0 8px 8px -6px #333;
  color: #222222;
  padding: 0px 0px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, .5);
}
<nav>
  <ul id="tabs">
    <li>
      <a href="#home" style="font-weight: bold;">Home</a>
    </li>
    <li>
      <a href="#products" style="font-weight: bold;">Products</a>
    </li>
    <li>
      <a href="#order" style="font-weight: bold;">Order</a>
    </li>
    <li>
      <a href="#settings" style="font-weight: bold;">Settings</a>
    </li>
  </ul>
</nav>

Answer №1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
  <!-- Copyright of this page belongs to Tech Solutions Inc. -->

    <title>Sample JavaScript tabs</title>

  <style type="text/css">
   body { font-size: 80%; font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; }
   ul#tabs { list-style-type: none; margin: 30px 0 0 0; padding: 0 0 0.3em 0;       }
   ul#tabs li { display: inline; }
   ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px  solid #c9c3ba; border-bottom: none; padding: 0.3em; text-decoration: none; }
   ul#tabs li a:hover { background-color: #f1f0ee; }
   ul#tabs li a.selected { color: #000; background-color: #f1f0ee; font-weight: bold; padding: 0.7em 0.3em 0.38em 0.3em; }
   div.tabContent { border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; }
  div.tabContent.hide { display: none; }
 </style>

 <script type="text/javascript">
 //<![CDATA[

 var tabLinks = new Array();
 var contentDivs = new Array();

 function initializeTabs() {

  // get the tab links and content divs
  var tabListItems = document.getElementById('tabs').childNodes;
  for ( var i = 0; i < tabListItems.length; i++ ) {
    if ( tabListItems[i].nodeName == "LI" ) {
      var tabLink = findFirstChildWithTag( tabListItems[i], 'A' );
      var id = getIdFromHash( tabLink.getAttribute('href') );
      tabLinks[id] = tabLink;
      contentDivs[id] = document.getElementById( id );
    }
  }

  // set onclick events and highlight first tab
  var i = 0;

  for ( var id in tabLinks ) {
    tabLinks[id].onclick = switchTab;
    tabLinks[id].onfocus = function() { this.blur() };
    if ( i == 0 ) tabLinks[id].className = 'selected';
    i++;
  }

  // Hide all content divs except the first
  var i = 0;

  for ( var id in contentDivs ) {
    if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
    i++;
  }
 }

  function switchTab() {
   var selectedId = getIdFromHash( this.getAttribute('href') );

   // Highlight the selected tab, and dim all others.
   // Also show the selected content div, and hide all others.
   for ( var id in contentDivs ) {
    if ( id == selectedId ) {
      tabLinks[id].className = 'selected';
      contentDivs[id].className = 'tabContent';
    } else {
      tabLinks[id].className = '';
      contentDivs[id].className = 'tabContent hide';
    }
  }

  // Prevent following the link
  return false;
   }

   function findFirstChildWithTag( element, tagName ) {
    for ( var i = 0; i < element.childNodes.length; i++ ) {
     if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
    }
   }

 function getIdFromHash( url ) {
   var hashPos = url.lastIndexOf ( '#' );
   return url.substring( hashPos + 1 );
 }

 //]]>
  </script>
 </head>
 <body onload="initializeTabs()">
  <h1>Sample JavaScript tabs</h1>

   <ul id="tabs">
  <li><a href="#about">About JavaScript tabs</a></li>
  <li><a href="#advantages">Advantages of tabs</a></li>
  <li><a href="#usage">Using tabs</a></li>
   </ul>

    <div class="tabContent" id="about">
    <h2>About JavaScript tabs</h2>
    <div>
    <p>JavaScript tabs organize your webpage content into tabbed sections, displaying only one section at a time.</p>
    <p>The code ensures graceful degradation on browsers without JavaScript or CSS support.</p>
   </div>
   </div>

   <div class="tabContent" id="advantages">
   <h2>Advantages of tabs</h2>
   <div>
    <p>JavaScript tabs are ideal for webpages with substantial content.</p>
    <p>They work well for multi-step web forms and similar tasks.</p>
  </div>
  </div>

  <div class="tabContent" id="usage">
  <h2>Using tabs</h2>
  <div>
    <p>Click on a tab to view its content. Utilizing tabs is simple and effective!</p>
  </div>
  </div>


 </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

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...

Is nesting possible with the &:extend function in LessCss?

I've recently been exploring the Less &:extend feature. My goal is to nest multiple extends - essentially extending a class that itself extends another class. However, after testing it out, I'm not sure if it's working as expected. It ...

Securing JSON-based RESTful services

I am in the process of developing a web application, where I have established a clear separation between my "frontend" server using Lighttpd to serve index.html and javascript. My frontend, powered by Backbone.js, is connected to my Node.js backend webser ...

Icons will be displayed when hovered over

Is it possible to display icons on hover in a div and hide them otherwise using just CSS? Or do I need to use javascript for this function? Thanks in advance! Example: HTML: <div id="text_entry"> <p>Some text here</p> <span ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

How can I anchor a div Banner saying "Get 50% off our products" to the Navbar directly above it?

Bootstrap Question: How can I attach the div Banner ("50% off of our products") to the Navbar directly above it? The structure looks like this: <Navbar> </Navbar> <div> <span>Discount: 50% off of our products </span </di ...

The error message "MongoDB encountered an issue with accessing the property 'push', as it was undefined."

Exploring node.js, express and MongoDB is a learning journey for me. While working on data association in MongoDB models, I encountered a runtime error. Even though the reference has been added to the model, the push() method fails to recognize it. Here ar ...

The Material-UI Snackbar stubbornly refuses to disappear even after setting its controlled state to false

I am currently working with a Snackbar component that relies on the redux state for control. I have implemented the onRequestClose() function in an attempt to disable the clickaway close feature. However, I have encountered an issue where setting the prop ...

When implementing v-model on a v-dialog component, it causes the element within an array to

There is an array of apps with links, and a Dialog component that has v-model="dialog" to close it. However, after adding v-model to the v-dialog, the functionality of the apps is affected. The current app is passed as a prop to Dialog, but it always sends ...

CSS transformation incomplete

I am currently creating a scrolling ticker animation for my website. Here is the HTML code: <div class="top-news"> <div class="t-n-c"> <div class="textwidget">Latest News: Our first 20 customers get 20% off their fi ...

Is it possible to change the return value of an Object key to something other than a string in REACT? Issue with RE

In an attempt to modify the data in an object using the setState method in 'react', I decided to take a different approach. Instead of creating a function for each key in the state object, I attempted to create one object and return the key from ...

Tips for including a decimal point in an angular reactive form control when the initial value is 1 or higher

I am trying to input a decimal number with 1 and one zero like 1.0 <input type="number" formControlName="global_velocity_weight" /> this.form = this.fb.group({ global_velocity_weight: new FormControl(1.0, { validators: [Valida ...

How to use Laravel to upload images using Ajax

My database table structure for users is as follows: id (integer) firstname (string) lastName (string) email (string) login (string) password (string) image (text) I want to be able to insert an image along with the user data using Ajax and jQuery. How ...

Is Webkit's Overflow Scrolling feature hiding the divs on your website?

I recently implemented a design for my website where the content is contained within an absolute positioned div that takes up the entire screen. However, I noticed that the scrolling on this div felt clunky and not as smooth as I would like it to be. After ...

Double Triggering Problem Arises During Partial Refresh

My dojo button bar is connected to a csjs function that performs a partialrefreshget() on a datable control. The datasource for the datatable control is a view. Within the this.keys property, I have implemented logic to check if the partialrefresh was ini ...

Complete the loop of ajax calls array instead of terminating when an error occurs in one of the calls

I am attempting to create a loop of ajax calls from an array and save each data result to be printed once all calls have been successfully received. The issue arises when any ajax call returns an error, causing the entire process to be aborted and the cal ...

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 ...

Save information to a server-side .xml file with the use of either JavaScript or PHP

I have a website built using HTML and JavaScript. Currently, I am successfully retrieving data from a server-side .xml file on the site. Everything is working perfectly! However, I am facing issues with allowing users to input data into a field and save ...

When the user saves the changes on the pop-up window, the main window will automatically refresh

I currently have a calendar feature that allows users to create, edit, and delete appointments. When a user clicks on the new appointment button, it opens a window above the calendar interface. Once the user fills out the necessary fields and clicks save, ...

What are the steps to implement IndexedDB in an Angular application?

I'm searching for a solution to utilize indexedDB within Angular. I need assistance with implementing data recovery or potentially using a browser-based database that doesn't have the 5 MB limit like localStorage. Can anyone point me in the right ...