What is the best way to implement an active tab feature using jQuery that changes based on the current page being viewed?

Are you looking to create an active tab effect in a navigation bar, but your links are on different pages? Fear not, there is a way using Jquery to fetch the url and make the tab active.

In this example, we give the specific tab a class "active":

var tabs = $('ul.tabs');

    tabs.each(function(i) {
        //Get all tabs
        var tab = $(this).find('> li > a');
        tab.click(function(e) {

            //Get Location of tab's content
            var contentLocation = $(this).attr('href') + "Tab";

            //Let go if not a hashed one
            if(contentLocation.charAt(0)=="#") {

                e.preventDefault();

                //Make Tab Active
                tab.removeClass('active');
                $(this).addClass('active');

                //Show Tab Content & add active class
                $(contentLocation).show().addClass('active').siblings().hide().removeClass('active');

            } 
        });

If you want this to work with links to other pages within your site, alter the html like so:

<ul id="nav"  class="tabs">
    <li><a href="/" title="Home" class="active">Home</a></li>   
    <li><a href="/about/" title="About us">About</a></li>
    <li><a href="/demo/" title="Demo">Demo</a></li>
    <li><a href="/where/" class="dir" title="Where">Where</a></li>
    <li><a href="/contact/" class="dir" title="Contact Us">Contact Us</a></li>
</ul>

The jquery provided above currently only works for #tab1, #tab2 etc. To make the tab active depending on the current page name, some adjustments might be necessary. Sorry if this is a bit unclear, the concept can be tricky to explain!

Answer №1

When the page loads, you can use the 'window.location' object to identify which page is being viewed, and then apply the 'active' class to the corresponding link:

$(document).ready(function () {
    // Check each link against the current window location
    var loc_href = window.location.pathname;
    $('#nav a').each(function () {
        if (loc_href == $(this).attr('href')) {
            $(this).addClass('active');
        }
    });
});

Please note that the comparison line 'loc == $(this).attr('href')' confirms an exact match between the link href values and the current window.location.pathname string.

Answer №2

document.URL

This will retrieve the URL of the current page, allowing you to modify your if statement as follows -

if (document.URL.includes(contentLocation)) {

This code snippet will verify whether the clicked link's URL is within the current page's URL. Feel free to adjust this algorithm according to your requirements.

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

Tips for adjusting text placement on a Bootstrap responsive webpage:

Hey there, I hope everything is going well. I'm facing a little issue here. I'm trying to design a page layout that looks like this: Image - Description Description - Image Image - Description and so on... However, when viewed on a smaller devi ...

Tips for eliminating the entire link from the footer section

Whenever a link is hovered over, a white box displaying the full URL appears at the bottom left of the browser. Is there a way to remove this feature from my website? I appreciate any assistance with this issue. Thank you! ...

How to locate and adjust the camera's position in three.js?

I am utilizing THREE.OrbitalControl.js Control = new THREE.OrbitControls(Camera, Renderer.domElement); As I rotate and move the mesh to locate the camera position, I print out the values of Camera.position and Camera.rotation in the animate function. Ho ...

Iterating through a series of Axios requests nested within each other to handle pagination in an

I need help iterating through the API response that includes pagination. Below is a snippet of the API response: { count: 165, next: "http://example.com/name?offset=30&per_page=30", previous: null } Here is my useEffect hook: const [datas, se ...

How can the JSRuntime windows show a list of all the records?

I'm currently tackling a Blazor Server project with a unique requirement: displaying records in a popup and then converting them into a PDF document. However, I've encountered an issue where if the records exceed a single page, the PDF only captu ...

The Ajax request fails to trigger the success function following the JsonResult response

Attempting to utilize Ajax to add a record to the database and retrieve data from JsonResult upon successful insertion leads to an error message: parseerror. Oddly enough, the record is successfully added to the DB. Below is the code for the post method: ...

Choosing our hourly availability?

I came across a reference to a similar question on Stack Overflow. Although I attempted to find a solution, I have not been successful so far. <div class="form-group"> <label>Working Hours :</label> <div v-for="value in day" c ...

JavaScript form validation eliminates input data

I recently started using the JavaScript library for client-side form validation called Bouncer. It has been working really well, but I have encountered a peculiar behavior that I need help understanding. My form has two submit buttons with different value ...

Text alignment from the lower edge

Imagine having a title inside an image, positioned near the bottom with a negative margin-top. The issue arises when the text orientation expands from top to bottom as more content is added. Is there a way to reverse this, so that the text div grows toward ...

Is it dependable to use jQuery to trigger ajax upon click in order to reliably work sequentially on the database?

Imagine there are 4 radio buttons on a webpage, and when any of them is clicked, it triggers an ajax call to save the button's value in a database. If the user clicks the first radio button (with a value of 1), an ajax call will be made to save this ...

Find the sum of object prototype differences in JavaScript

Struggling with a JavaScript challenge - I need help creating a JavaScript script where the user inputs the month and the amount of rain for that month, and the program generates a table showing the total rain for each repeated month. For example, if Janua ...

My JSON request seems to be malfunctioning and I can't figure out why

I've generated a URL that I need to forward to the police data API. var api_url="http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q="+latlon; document.write(api_url); The URL functions correctly when manually entered into a browser, but I requir ...

Is there a way to make React.js TypeScript recognize 'parentElement' on 'event.target' when using onKeyDown event?

I have developed a specialized accessible component using React TypeScript for screen readers. I am facing issues defining keys for navigation and focusing within the table element due to type errors that I can't seem to resolve. The error message I ...

Can the order of event bubbling be altered in JavaScript?

I have three boxes in my HTML, each with its own click events. Currently, when I click on a child element, event bubbling occurs in the order of C->B->A. However, I am curious to see if it's possible to change the event bubbling order to C-> ...

The jQuery statements are not properly executing the if and else conditions

i'm currently assessing the condition using this particular code. jQuery(document).ready(function($){ $('#uitkering_funds').hide(); $('#uitkering_funds_hoofd').hide(); $('#partner_uitkering').hide(); $('#par ...

Activating the change event in jQuery: A step-by-step guide

Within my ASP.NET page, I have included a UserControl that contains a RadioButtonList. Whenever an item in the RadioButtonList is changed, I need to trigger the following jQuery function: $('#rdlUser').change(function (e) { alert("change fun ...

Having difficulty retrieving the value of a dynamically generated cell with document.getElementById

I have been facing an issue with adding rows to an HTML table that already contains 2 rows, using the following JavaScript code: <table id="dataTable" class="CSSTableGenerator"> <tbody> <tr> <td>< ...

HTMLunit - error: [MobX] Unable to access proxy

Currently, I am faced with a challenge in extracting data from a JavaScript-based website using htmlunit. My approach involves calling the site through webClient.getPage, but this method is triggering an exception. public static void main(String[] args ...

The error function in Ajax is always triggered. What steps can be taken to address this issue?

After triggering the AJAX call, it routes to the controller which then executes the error function in response. AJAX snippet : <script> function showEmpDetails(empid) { console.log(empid); $.ajax({ url: "employeeInfo", type: ...

Utilize Paper.js PointText to Obtain Baseline Coordinates instead of Starting from the Bottom Left Corner

Check out this Paper.js sketch. Click on "TEXT" to view the bounding box. It's worth noting that I configured the leading property to match the font size, though by default it is typically 1.2 times the font size as stated in the documentation. Why d ...