Customizing tab menu functionality for specific click actions

I have created a simple HTML tab menu with JavaScript that allows for changing content when tabs are clicked.

test.html

<!DOCTYPE html>
<html>
<head>
    <title>My Menu Test</title>
    <style type="text/css" media="all">@import "public/stylesheets/master.css";</style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
    <script><!--
        $(document).ready(function() {
            $('.tablist > li > a').click(function(event){
                event.preventDefault();//stop browser to take action for clicked anchor

       //get displaying tab content jQuery selector
       var active_tab_selector = $('.tablist > li.active > a').attr('href');                    

       //find actived navigation and remove 'active' css
       var actived_nav = $('.tablist > li.active');
       actived_nav.removeClass('active');

       //add 'active' css into clicked navigation
       $(this).parents('li').addClass('active');

       //hide displaying tab content
       $(active_tab_selector).removeClass('active');
       $(active_tab_selector).addClass('hide');

       //show target tab content
       var target_tab_selector = $(this).attr('href');
       $(target_tab_selector).removeClass('hide');
       $(target_tab_selector).addClass('active');
    });
});
    //--></script>

    </head>
    <body>
    <div id="page-container">
    <div id="main-nav">
        <ul class="tablist">
            <li class="active"><a href="#tab1">Tab1</a></li>
            <li><a href="#tab2">Tab2</a></li>
            <li><a href="#tab3">Tab3</a></li>
            <li><a href="/logout">Logout</a></li>
        </ul>
    </div>
    <div id="content">
        <section id="tab1" class="tab-content active">
            <div>
                Content for Tab1 
            </div>
        </section>
        <section id="tab2" class="tab-content hide">
            <div>
                Content for Tab2
            </div>
        </section>
        <section id="tab3" class="tab-content hide">
            <div>
                Content for Tab3
            </div>
        </section>
    </div>
    </div>
    </body>
</html>

master.css

.tablist { list-style: none; height: 30px; padding: 0; margin: 0; border: none; }
.tablist li { float:left; margin-right: 3px; }
.tablist li a { display:block; padding:0 16px; text-decoration:none; border: 1px solid #babdb6; border-bottom:0; font:bold 14px/32px arial,geneva,helvetica,sans-serif; color:#000; background-color:#ccc;

/*===  CSS 3 elements  ===*/
webkit-border-top-right-radius: 5px;
-webkit-border-top-left-radius: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-topleft: 5px;
border-top-right-radius: 5px;
border-top-left-radius: 5px;
}

.tablist li a:hover { background:#babdb6; color:#fff; text-decoration:none; }


.tablist > .active > a,
.tablist > .active > a:hover { color: #555555; cursor: default; background-color: #ffffff; border: 1px solid #ddd; border-bottom-color: transparent; }

.tab-content.active{ display: block; }

.tab-content.hide{ display: none; }

In the current setup, clicking on Tab1, Tab2, or Tab3 displays the respective div while hiding others. However, I seek advice on how to handle different actions upon clicking the Logout tab without affecting its appearance like the other tabs. Can the logout tab redirect me to "/logout" instead of behaving like the other tabs?

My Question for now: I want a unique action triggered by clicking the Logout tab without altering its visual style. Is it possible to direct the user to a logout page ("/logout") upon clicking this specific tab while maintaining the tab's appearance as consistent with the rest of the menu?

Thank you!

Answer №1

I really like the concept of omitting the logout button from the click function altogether and creating its own handler, as demonstrated by @xCRKxTyPHoon. However, if you still want to use the click function and be able to easily add more links in a similar manner without writing separate handlers for each, you could implement something like this at the beginning of the click function (it checks if the href attribute contains a slash and redirects if it does):

if($(this).attr('href').indexOf('/') !== -1){
  window.location = $(this).attr('href');
}

Check out this pen with that code snippet: http://codepen.io/shigidaMark/pen/YqNWRy

Answer №2

If you use the selector $('.tablist > li > a'), you will be able to locate all anchor tags that are nested within the 'tablist' class object. It's important to note that this selection also encompasses your logout tag:

<a href="/logout">Logout</a>
. As a result, your logout tab behaves similarly to the other tabs.

To exclude the logout tab from this loop, there are various approaches that can be taken. One straightforward method is assigning an ID to the anchor and utilizing a :not selector:

<a id="logout" href="/logout">Logout</a>

The updated loop selector would then appear as follows:

$('.tablist > li > a').not('#logout')

By excluding the tab using this code snippet, you'll have the ability to manage it separately and redirect it to the desired page.

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

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

Strategies for creating a grid-inspired layout: tips and tricks

Recently, I've been tasked with creating a catalogue section for our e-commerce site. My designer came up with this layout which I find really appealing, but I'm having trouble figuring out how to implement it. I attempted using tables, but it di ...

Implementing clickable table rows in React Router Link for seamless navigation

I'm relatively new to working with React. In my project, there is a Component called Content, which acts as a container for two other components - List and Profile. class Content extends Component{ <HashRouter> <Route exact path="/ ...

The OpenWeatherMap API is displaying 'undefined' as a response

I've been encountering some issues with my weather app project due to lack of clarity in my previous questions. To be more specific, every time I attempt to retrieve weather information in JSON format using the fetch method, it keeps returning undefin ...

Exploring the Dynamic Duo: Laravel Echo and JQuery

After including Echo in Vue.js' resources/assets/js/bootstrap.js, one of my components is throwing an error The error message states: "Error in mounted hook: 'TypeError: $ is not a function'" When I remove the Echo import, everything run ...

Dynamic import with require in Vue webpack not functioning as expected

Currently, I am in the process of developing an app that will be able to play various sounds. To achieve this functionality, I have created a NoiseMix component that will contain multiple Noise components. Each Noise component must have its own URL paramet ...

What is the best way to stretch the background image across both the footer and navbar for my app?

Here is the code snippet I am currently working with: <template> <v-app> <AppBar></AppBar> <v-main> <router-view></router-view> </v-main> <Footer></Footer> ...

What is the best way to send the value of a Select component from a child to a parent component in

Users have the ability to select a category, triggering the appearance of another dropdown menu based on their selection. I have created a separate component in a different file (.js) to handle this second dropdown. While I can see the data, I am wondering ...

When a d3 event is triggered by clicking, the value should be saved in a textbox

After clicking the checkbox, I would like to have all the checked client IP values automatically populate a textbox within the div called "ip." Here is my code snippet: <html> <body> <div id="ipDiv"> Client_ip :<input ty ...

Obtain the Row ID for Updating without Redirecting

A table in PHP/MySQL has been created with an edit button linked to each row. When the Edit button is clicked, it redirects to the same page but with the ID of the corresponding row item. This helps the PHP script retrieve the ID of the selected item. < ...

Footer placement not aligning at the bottom using Bootstrap

I'm having trouble getting my footer to stay at the bottom of my website without it sticking when I scroll. I want it to only appear at the bottom as you scroll down the webpage. Currently, the footer is positioned beneath the content on the webpage. ...

Issue with spacing dropdown choices within primary navigation bar

Struggling with my final project for a class as the semester comes to a close. I've received minimal help from my Professor and hit a roadblock. The main navigation on the side is working correctly, but the dropdown options are stacking on top of each ...

Manipulating Pixel Width and Height of Cells in Google Sheet using Apps Script

I'm looking for a solution to effectively retrieve and update the height and width in pixels of a Google Cell using Google Apps Script. While there is a built-in getWidth() function available, it only returns the width of the range in cells, which doe ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

What is the best way to showcase a list in three columns using PHP?

I've been struggling for hours to create a PHP code that will display a list in three columns with the following order: A D G B E H C F I Unfortunately, my current code only lists items in this order: A B C D E F G H I Here is the code I am curren ...

What is preventing my Express.js from running properly?

My express.js application stops running after reaching this point: node app.js info - socket.io started I'm looking for guidance on why this error occurs and how to resolve it. It seems like the issue lies within my app.js file, which I've inc ...

Modifying the CSS of the parent element using jQuery UI Draggable

After dragging a copy of the original element, I want to change the font color. How can I achieve this? jQuery("#tools-container .fieldset-item").draggable({ revert: "invalid", helper: "clone", cursor: "move", ...

Obtaining the MapOptions object from a map using Google Maps API version 3

Previously in Google Maps api v2, you were able to retrieve map parameters like the type and zoom directly from the map object. However, in version 3, the setOptions method is used to configure parameters, but there is no equivalent method like getOption ...

PHP Debate: Static vs Non-Static - Which is the Superior Choice?

Static and non-static functions as well as class properties really had me puzzled when I attempted to launch my website. Could someone clarify whether it is preferable to have the entire website coded using static functions rather than relying on non-stat ...

I'm having trouble with my delete function. How can I fix it?

When I try to use the delete function in Python to remove a user's post, it doesn't actually delete the post as expected. Instead, it just redirects the user back to the homepage without removing the post. Clicking the "delete link" should make t ...