What is the best way to create direct links to tabs using #anchors in JavaScript?

I am managing a website that includes info-tabs based on a template I found at this link. The tabs contain anchors like example.com/#convey, but unfortunately, direct links to specific tabs using #anchor do not work properly due to the tabs relying on JavaScript for functionality.

This is the JavaScript being used:

 /* fading the content in using a sub-menu */
    $('.content-fade-menu a').click(function(){
        var href = $(this).attr('href');
        var target = $('.content-fade').find(href);
        $('.content-fade-menu a').removeClass('active');
        $(this).addClass('active');
        $('.content-fade .content-fade-panel').hide();
        $(target).fadeIn('fast');
        return false;
    });

Here is the HTML code for the menu:

<ul class="sub-menu content-fade-menu">
<li><a href="#pi" class="">Personal Injury</a></li>
<li><a href="#employment" class="active">Employment</a></li>
</ul>

And this is the HTML for one non-active tab and one active tab:

<div class="content-fade">
<div class="content-fade-panel" id="pi" style="display: none;">
Non-active tab
</div> 
<div class="content-fade-panel" id="employment" style="display: block;">
Active tab
</div> 
</div>

What steps should I take to ensure that links such as example.com/#anchor function correctly?

Answer №1

Alright, I've successfully located the solution.

//Extract #anchor from the URL and locate the correct block
    var loc = window.location.hash;
    if (loc !== "") {
        var href = loc;
        var target = $('.content-fade').find(href);

//Deactivate the initial tab
        $('.content-fade-menu a').removeClass('active');

//Activate the appropriate tab
        $('.content-fade-menu a[href="' + href  +'"]').addClass('active');
        $('.content-fade .content-fade-panel').hide();
        $(target).fadeIn('fast');

//Scroll to the h3 heading of the activated block
        var zagolovok = $(target).find('h3');
        $('html, body').animate({scrollTop: $(zagolovok).offset().top}, 300);
    }

That concludes the process.

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

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Problem with sidebar animation: Functioning properly when open, but closes abruptly without animation in React using Tailwind CSS

When interacting with my Menu react component by clicking on the 'hamburger' icon that I created manually, the sidebar menu opens smoothly with an animation. However, the issue arises when trying to close the sidebar as it vanishes instantly with ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

Difficulty with formatting decimal points in JavaScript

I seem to be having an issue with decimal places in my code. Currently, it's showing the result as 123 123 12 but I actually need it to be displayed as 12 312 312. Is there anyone who can assist me with formatting this correctly? Here is the section ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

Checking for at least one matching pair in a JavaScript object

I have a pair of dictionaries that I need to compare in JavaScript. The goal is to determine if there is at least one identical key-value pair between them, not necessarily the entire dictionary being identical. my_dict = {"Text1":"Text1", "Text2":"Text3", ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

Creating seamless scrolling in ReactJS without any pre-built components

Can anyone guide me on how to implement an infinite scroll in reactJs using a JSON dataset? I prefer building it from scratch without relying on any library. {data?.map((conto) => { return ( <Suspense key={conto._uid} fallback={<p>Loadin ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Include scrollView on smaller screens based on conditions

While incorporating an overlay in my application, how can I integrate a ScrollView specifically for smaller devices? Initially, I am checking the width: const windowWidth = Dimensions.get("window").width; Subsequently, I am attempting to display the Scro ...

Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities. The issue I am encountering arises when repeating the second ng-repeat: <table class="table table-c ...

Retaining the data retrieved from a successful $.ajax call's done() function

After successfully retrieving the desired information in the done method, I encountered an issue when trying to assign it to a variable with broader scope. This approach had worked fine with $.each(...), leading me to assume that it would work here too. v ...

Using AngularJS and D3 to create a custom directive that allows for multiple instances of D3 loading within Angular applications

After creating an angular directive for a d3 forced-directed graph and using the code provided here, I encountered some issues with multiple loads. The directive seemed to load six times each time it was initialized, causing performance problems. To addres ...

Tips for providing the URL in JSON using Spring MVC

Every time I try to run my code, I encounter an issue where I cannot access the URL specified in the getJSON function. Below is my controller code: @RequestMapping(value = "branch") @Controller public class BranchController { @Autowired(required = true) ...

jQuery doesn't have the capability to convert this data into JSON format

I have some code that I want to convert into JSON format: var locationData = []; locationData['lat'] = position.coords.latitude; locationData['long'] = position.coords.longitude; locationData['address']['road'] = da ...

Troubleshooting problems with Bootstrap 3 inline datepicker beforeShowDay

Having created an inline datepicker, I have encountered a single issue - the inability to implement the beforeShowDay option. I utilize PHP to retrieve an array from a database, incorporating it with AJAX. Here's the code snippet: $(document).ready ...

Ways to identify if the text entered in a text area is right-to-left justified

Within a textarea, users can input text in English (or any other left-to-right language) or in a right-to-left language. If the user types in a right-to-left language, they must press Right-shift + ctrl to align the text to the right. However, on modern O ...