Having trouble getting custom tabs in jQuery to function properly?

I am facing an issue with a simple script I have created. The script is supposed to display a specific div when a user clicks on a link, and hide all other divs in the container. However, when I click on the link, nothing gets hidden as expected. Even after checking in firebug, there are no reported errors. Here's the code snippet:

javascript:

$(document).ready(function()
{




var linksToInt = { 
    "#pple": 0,
    "#serv": 1,
    "#sol": 2
}

$("a.div-link").click(function(){displayDiv($(this).attr("href"));});

function displayDiv(id){
var linkInt = linksToInt[id];
on_btn_click(linkInt);
}

function on_btn_click(displayDiv){
    displayDiv != null ? null : this;

    switch(displayDiv){
        case 0:
            function(){$("#content > div").hide(); $(displayDiv).show();};  
            break;
        case 1:
            function(){$("#content > div").hide(); $(displayDiv).show();};  
            break;
        case 2: 
            function(){$("#content > div").hide(); $(displayDiv).show();};  
            break;
        case 3:
            function(){$("#content > div").hide(); $(displayDiv).show();};  
            break;
}

});

markup:

<HTML>
<HEAD>
  <TITLE>Test</TITLE>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="application.js"></script>
 </HEAD>
 <BODY>
        <div id="sideLinks">
        <ul id="tabAbout">
            <li><a href="#pple" class="div-link">People</a></li>
            <li><a href="#serv" class="div-link">Service</a></li>
            <li><a href="#sol" class="div-link">Solutions</a></li>
        </ul>   
    </div>

<div id="content">
<div class="tabContent" id="pple">
    <p>
        Content
    </p>    


</div>

<div class="tabContent" id="serv">

    <p>
        Content
    </p>    

</div>

<div class="tabContent" id="sol">   
    <p>
        Content
    </p>    
</div>          
</div>

</BODY>
</HTML>

Any assistance would be greatly appreciated.

Answer №1

If you want to hide other divs without using the switch function, consider utilizing jQuery's .siblings function to select all elements except the desired one. I recently implemented something similar in my own project with success.

Here is the code snippet where I use .siblings:

$(this).siblings().removeClass('selected');
$(this).addClass('selected');

To toggle the displayed div based on user selection:

selection = $(this).attr("id");
$(this).addClass('selected');
$("div#"+selection).siblings().hide();
$("div#"+selection).show();

In my case, users click on a list item to choose an item, but the concept remains the same. I tweaked the second code snippet to align with your approach of using .siblings for hiding. Initially, I used a class selector to hide elements, but I see the benefit of switching to siblings now.

I hope this explanation proves helpful to you.

As an edit, here’s an adjusted version of the code matching yours...

    selection = $(this).attr("href");
    $(".tabContent").hide();
    $("div#"+selection).show();

You can incorporate this simple solution within your displayDiv function for managing showing and hiding of elements.

Answer №2

According to the advice from a fellow coder, it seems like you have a missing curly bracket on the last line.

In your on_btn_click function, it appears that your displayDiv is being assigned a number. Attempting to use a selector on a number will not work as expected, resulting in an empty return value. You should replace $(1) with "#pple". If you prefer to store it in a variable, ensure that it allows access to both the id and the selector.

Additionally, the code within your on_btn_click function seems to be ineffective. Instead of utilizing a separate function in each case block, consider incorporating your code inline. Your revised code should resemble this:

 $(document).ready(function() {
var linksToInt = { 
    "#pple": 0,
    "#serv": 1,
    "#sol": 2}


$("a.div-link").click(function(){displayDiv($(this).attr("href"));});



function displayDiv(id){
var linkInt = linksToInt[id];
on_btn_click(linkInt);
}



function on_btn_click(displayDiv){
    displayDiv != null ? null : this;

    switch(displayDiv){
        case 0:
            $("#content > div").hide(); 
            //displayDiv has a value of '0', so you can't do $(0), it won't return anything             
            $("#pple").show();  
            break;
        case 1:
            $("#content > div").hide();
            $("#serv").show();  
            break;
        case 2: 
            $("#content > div").hide();
            $("#sol").show();  
            break;
        case 3:
            $("#content > div").hide();
            $(displayDiv).show();  
            break;
    }
}});

Answer №3

There seems to be a bracket missing on the final line. The correct format should be

}});

instead of

});

You might want to consider using the jQuery UI Tabs module found at http://jqueryui.com/demos/tabs/ instead of creating something from scratch. It offers extensive customization and is user-friendly.

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

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

Error 405 - Invalid request method

Here is my JQuery code for calling a web API: let request = { RequestId: "123", DeviceId: "ACU-B2-01-R1", AccessType: "Unlock", LoginId: "tester", Password: "tester" }; $.ajax({ url: 'http://localhost:55208/api/accesspanel&ap ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

What is the best way to create a keyup event for the entire document except for one specific element?

Looking for some advice on how to handle a specific code scenario. Here's what I have: $(document).ready(function(){ $(document).on("keyup",function(e){myFunction(e)}); }); function myFunction(e){ console.log("hi"); } In ...

Guide on creating an HTML5 rectangle for reuse using the Prototypal Pattern

I'm struggling to grasp Prototypal Inheritance through the use of the Prototypal pattern by creating a rectangle object and an instance of that rectangle. It seems like it should be straightforward, but I'm having trouble understanding why the Re ...

Using the URL parameter in a jQuery AJAX request

When I try to make an ajax call from a modal window, the request URL doesn't seem to be correct. My webserver is set up to accept URLs like http://localhost/search, but not file:///search. How can I fix this issue? I have posted more details about wh ...

jquery logic for iterating through all elements in a select menu encountering issues

In search of a solution to iterate through all options in a dropdown list using code, comparing each to a variable. When a match is found, I aim to set that particular value as the selected item in the dropdown and then exit the loop. Here's what I&ap ...

CSS: Obtain a button and align it to the "a" element

Feeling a bit puzzled: https://i.stack.imgur.com/S7xKh.png In the image, there's a span button labeled "Navigation einblenden", and a span a tagged as "Suche". Despite styling them identically: In the CSS snippet, dispOpts is the parent span's ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

When using equal-width columns in Bootstrap, the columns will be stacked one on top of the other

When I utilize Bootstrap 5, I am encountering an issue where equal width columns are being displayed one underneath the other. To illustrate, here is a simple example directly from the Bootstrap website: <link rel="stylesheet" href="https://cdn.jsd ...

What is the best way to adjust the height of my website to properly display on all screen sizes

Is there a way to make my web page fit perfectly on the screen in terms of both width and height? I'm familiar with using Media Queries for adjusting widths, but how can I also control the height? Any suggestions on setting the height? I would great ...

Interacting with a PNG file using a border radius in Internet Explorer 9 is causing issues with its transparency

Encountering an issue with IE9 where a white to gray gradient box appears around the transparent PNG on hover/selection. There is also a border radius applied to the thumbnail. Any ideas on how to fix this problem? Here is an example of the issue: https ...

Is the "footer" div automatically nested within the "main" div if they are not nested in the code?

Within my code structure, I currently have the following: <html> <head> ... </head> <body> <div id="body"> <div id="main"> ... </div> <div id="foot ...

How to effectively execute AJAX requests on the server side using Node.js

I am currently in the process of developing a search engine that utilizes both Twitter and Wiki APIs on the server-side after receiving a search query from the client. Previously, when operating solely on the client-side, my AJAX request to the Wiki API lo ...

Recurrence of solely the middle segment of the separator's background picture

I have a unique divider image with fading top and bottom parts. I'm wondering if it's possible to use a sprite and 3 divs to only repeat the middle section, considering that my height is variable. Do I need separate images for the top, middle, an ...

Is there a way to eliminate the additional gap found at the bottom of a div element?

I've been encountering some difficulty when trying to insert an image into a div without any padding. The issue I'm facing is that the sizing doesn't seem to be correct; there's unnecessary extra space at the bottom. Despite my efforts ...

HTML numbered list - precise sequence

Can I customize the format of my ordered list in HTML/CSS to look like this? o. Item 1 i. Item 2 ii. Item 3 iii. Item 4 Is it feasible to create a custom format for ordered lists using HTML and CSS? ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

The Python socket fails to receive a valid response after sending an HTTP 1.1 CONNECT request

I am attempting to create a simple program that establishes an https tunnel with www.google.com on port 443. Initially, I used the code below: import socket def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("www.google. ...

Waiting for Asynchronous Response in Jquery with Ajax

Attempting the following code to fetch multiple URLs within a for loop and store all data in the text variable. After the completion of the for loop, trying to check the value of text but receiving 'undefined'. It seems like the AJAX calls have n ...