Is it possible to open a new tab by clicking on an anchor tag

I have a scenario with two tabs on a webpage, each with anchor tags that I can navigate to from the homepage using a header menu item anchor. The tabs are working fine with an active class and aria-expanded="true", but I'm facing an issue where the appropriate tab does not automatically become active when clicking on the header menu item.

For example: 1. Click on the #tab2 link in the header menu 2. Page loads, scroll to anchor tag, but tab1 remains open instead of tab2

I have attempted changing the active class, but I am relatively new to javascript/jquery and unsure if I am doing it correctly. Additionally, this is in WordPress and the header menu does not have an id field for its elements.

===============================

EDIT, CLARIFICATION: The tabs are functional, and I can access them from the header link. I just need the correct tab to be open based on the header link clicked.

I also tried using a .click(#tab2) function, but the script did not execute properly.

if(window.location.href.indexOf("tab2") > -1) {
       document.getElementById('tab2').click();
    }

Edit: Header HTML for link:

<ul class="uk-nav uk-nav-navbar">
        <li class="uk-active">
            <a title="" href="testsite.com/#tab1" >tab 1</a></li>
        <li class="uk-active"><a title="" href="testsite.com/#tab2" 
            class="">tab2</a>
        </li>
    </ul>

Tab HTML

    <li class="uk-width-medium-1-4 active" id="tab1" aria-expanded="false">
        <a class="uk-button tab1">tab1</a>
    </li>
    <li class="uk-width-medium-1-4 " id="tab2" aria-expanded="false">
        <a class="uk-button tab2">tab2</a>
    </li>

Javascript:

var ai = document.getElementById(""); [I'm having trouble with this, cause I can't see a way to attach an id to a wordpress menu item]

var ch = document.getElementById("");

ai.onclick = function(){
    document.getElementById('tab1').click();
}

ch.onclick = function(){
    document.getElementById('tab2').click();
}

Answer №1

If you want to experiment with jQuery, you can give it a try. I've included a sample code snippet below for reference. Take a look:

<!DOCTYPE html>
<html lang="en>
<head>
  <title>Sample Page</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Dynamic Tabs</h2>
  <p>To create toggleable tabs, assign the data-toggle="tab" attribute to each link. Also, add a .tab-pane class with a unique ID for each tab and enclose them within a div element with class .tab-content.</p>

  <ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
    <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="tab" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="tab" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
    </div>
  </div>
</div>
<script type="text/javascript">
$(document).ready(function(){
    var anchorHash = window.location.href.toString();
    if( anchorHash.lastIndexOf('#') != -1 ) {
        anchorHash = anchorHash.substr(anchorHash.lastIndexOf('#'));
        if( $('a[href="'+ anchorHash +'"]').length > 0 ) {
            $('a[href="'+ anchorHash +'"]').trigger('click');
        }
    }
});
</script>
</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

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Are moment.js and moment.php interchangeable?

Recently, I developed a JavaScript script utilizing moment.js and I am looking to mirror it using a cron job in PHP. In my search for moment.js equivalents in PHP, I came across this https://github.com/fightbulc/moment.php ...

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

Is there a way to update the state for a specific location on a map?

I have a requirement to update the quantity of a product by using setCount. let [product.quantity, setCount] = useState(product.quantity); Implementing increment and decrement functions for product.quantity const increaseQuantity = () => { setCoun ...

Invoke a Node.js script from a Spring Boot application to pass a Java object to the script. The script will modify the object and then return it back to the originating class

class Services { Address address = new Address(....); /* Invoke NodeJs script and pass address object In the js script modify address object var address = getAddress() Modify address object Return address obj ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

The JQuery function has not been defined within the scripts file

It seems like my jquery function is suddenly undefined and I can't figure out why. I made sure to call jquery before the scripts file, so that's not the issue. Strangely, the jquery was functioning properly until I placed it inside this specific ...

Error message: "Attempting to update /mytable using the `UPDATE` SQL command on React App localhost:MYPORT with react-postgres and PostgreSQL / node.js backend is not allowed."

Following the tutorial located at https://github.com/nsebhastian/react-node-postgres, I have successfully implemented the full guide, as evidenced by the results documented in TypeError: Cannot read property 'rows' of undefined. The functionalit ...

Having trouble making SCSS mixins work with CSS variables in NextJS?

My current next.config.js setup looks like this: module.exports = (phase, {defaultConfig}) => { if ('sassOptions' in defaultConfig) { defaultConfig['sassOptions'] = { includePaths: ['./styles'], ...

Snap.js and bootstrap causing padding where the scrollbar is supposed to be visible on android devices

I am currently using snap.js (jakiestfu) along with bootstrap. On my Android device, when I view the page using the standard "internet" browser, I notice a padding where the scrollbar would typically appear in a normal browser (refer to image ). This extr ...

"Access denied" error when using Internet Explorer and jQuery

Attempting to make an AJAX call using jQuery's $.post in Internet Explorer is resulting in an error message stating "Permission denied." This peculiar issue only seems to occur when accessing a page after having visited another page. For example, if ...

How to vertically align a div or input element with Bootstrap

https://i.sstatic.net/2OHp2.png This is the code I'm currently using: <body class="bg-light"> <div class="row justify-content-center mt-3"> <div class="col-6"> <in ...

Having trouble getting the jQuery toggle function to work properly with div elements

I'm struggling with some divs that are not behaving as expected. When I click the button, it opens and changes the text to "Collapse", but when I click it again, it doesn't change the text back to "Find Support". Additionally, if I click on a dif ...

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

Trigger JQuery function post CSS styling completion

Upon using $(document).ready(function() {...}, it seems that the function is invoked after the DOM has loaded, but potentially before CSS styles have been completely applied. My goal is to obtain the width of a particular element. Strangely, when attempti ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

Creating Projects Without a Build System in Sublime Text 3

I'm having trouble getting the sublime build system to function properly. When attempting to run my code, I receive a "No Build System" error message. I have already set the build system to Automatic under Tools->Build Systems and saved the file a ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...