Jquery solution for toggling multiple Divs individually

I'm currently working on a small application that has both a sidebar menu and a header menu. My goal is to have all items in these menus toggle the visibility of content in one main window or page. When a button is clicked, I want it to show the corresponding section and hide all other sections.

<a id="linktodiv1">Show Window 1, hide other windows</a>
<a id="linktodiv2">Show Window 2, hide other windows</a>
<a id="linktodiv3">Show Window 3, hide other windows</a>
<div id="linktodiv4">Show Window 4, hide other windows</div>

<div id="window1">content</div>
<div id="window2">content</div>
<div id="window3">content</div>
<div id="window4">content</div>

Does anyone know the best or cleanest way to implement this functionality using jQuery? Any help would be greatly appreciated. Thanks!

Answer №1

Using indexing to display content in order on a page

var $links = $('[id^=linktodiv]'),// storing elements as variables
    $content = $('[id^=window]');

$links.click(function(){
    // hiding all content and showing corresponding index content window
    $content.hide().eq( $links.index(this) ).show();        
});

Assigning common components with a shared class can be very helpful

CHECK OUT DEMO

Answer №2

Make sure to assign specific classes to your links and divs. For example, use .showHide for links and .contDiv for divs. Assuming they are in the same order:

$('.showHide').on('click', function() {
    $('.contDiv').hide('slow');
    $('.contDiv').eq($(this).index()).show('slow');
});

Check out the jsfiddle DEMO here.

Answer №3

If you're in need of a solution that provides a sleek and organized interface, consider implementing the jquery accordion method from the jquery UI library. You can find more information about it here: https://jqueryui.com/accordion/, which seems to align perfectly with your requirements.

For a practical example, check out this demo on JSFiddle: http://jsfiddle.net/d6mSA/616/

The code snippet you'll need is:

<div id="accordion"> 
    <h3><a href="#">Show Window 1</a></h3>
    <div>
        <p>Section 1 Content</p>
    </div>
    <h3><a href="#">Show Window 2</a></h3>
    <div>
        <p>Section 2 Content</p>
    </div>
    <h3><a href="#">Show Window 3</a></h3>
    <div>
        <p>Section 3 Content</p>
    </div>
    <h3><a href="#">Show Window 4</a></h3>
    <div>
        <p>Section 4 Content</p>
    </div>
</div>

JQUERY

$(function () {
    $("#accordion").accordion({
        autoHeight: true
    });
    $("#accordion").accordion({
        collapsible: true
    });
});

Answer №4

If you're in search of tabs, there are various options available for you to consider.

For starters, if you have bootstrap loaded on your page, you can refer to this link:

http://getbootstrap.com/javascript/#tabs

Alternatively, if you already have jQuery UI installed or are open to loading it, you may find this link useful:

https://jqueryui.com/tabs/

In case you don't have either but are willing to incorporate a plugin, you can explore options such as:

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

Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

jQuery AJAX issues on Safari and iOS gadgets

I'm facing a compatibility issue specifically with Safari and all iOS devices. I've developed this jQuery code for a project, but it seems to have trouble working with Safari. Interestingly, it works perfectly fine with Chrome, Firefox, and even ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Integrate Geometric Information into PostGIS

Hi there! I'm currently using a combination of postgresql and node.js for my backend operations. I've been trying to insert a point into the database from the frontend, but unfortunately, I keep encountering an error message stating "value too lo ...

What size should I use for creating a responsive website?

After scouring the internet, I stumbled upon numerous dimensions referred to as proper for developing responsive designs. However, I am specifically interested in identifying the ideal breakpoints, particularly for mobile devices with small screens like ...

How can I change :hover to a clickable element instead?

I attempted to create a full-width accordion with the following code: .page { margin: 0; padding: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; height: 100vh; } .content { -webkit- ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

Elevate your website's design with Vue and create eye-catching CSS

I've been working on a Vue hamburger menu component, but I'm facing an issue with the animations. The animation process seems to reach the desired end result, yet there is no actual animation displayed. The animation triggering is done through a ...

How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to ...

JQuery not being recognized by MVC4 view

I encountered an issue with my @Html.DropDownList that is supposed to invoke a jquery function, but it seems that the function is not being called. I've attempted the following: $(document).ready(function () { $('.test').change(function ...

Problems during the installation of Webpack

Encountering Error Setting up Webpack and Babel with NPM npm ERR! Unexpected end of JSON input while parsing near '...pdragon":"^0.7.0","to' npm ERR! A complete log of this run can be found in: npm ERR! A complete log of this run can be found ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

Guide on plotting latitude and longitude coordinates on Google Maps with Vue.js through JSON data fetched via AJAX

I have implemented a Vue.js script to fetch JSON data through an AJAX request. However, I am encountering issues with the code. <script> new Vue({ el: '#feed' , data: { details: [], }, mounted() { this.$nextTick(fu ...

Is there a way to instantly show the contents of a newly opened tab in BootstrapVue?

Good day, my objective is as follows: Whenever a new tab is opened, it should become 'active' and display its content on the browser Issue: Currently, when a new tab is opened, the previous tab remains 'active'. Check out a simple e ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Leveraging Ajax with Google Analytics

Currently, I am working on a website that utilizes Ajax calls to update the main content. In order to integrate Google Analytics tracking code using the async _gaq method, I need to push a _trackPageview event with the URI to _gaq. There are two approaches ...

Deleting the main node in a JSON file containing multiple values

I am working with a JSON data stored in a variable. Here is the JSON Data: var employees = {"emp":{{"firstName":"John"},{"secondName":"John"}}}; My goal is to remove the emp node from the above JSON Data and have it as follows: {{"firstName":"John"},{" ...

Incorporating lodash into Angularjs for enhanced functionality

After stumbling upon an app online that utilizes AngularJS with Lodash, I noticed a simple way in which Lodash is incorporated. By including the following line in the body (after angular has been included): <script src='vendor/lodash/3.3.1/lodash. ...