Display a single div and conceal the rest upon clicking a link

Trying to find a way to hide all other divs when clicking on a navbar link to toggle them. Currently, the divs stay active when a new link is clicked. The goal is for them to slide up and the clicked one to slide down.

<script type="text/javascript>
$(document).ready(function(){

    $(".output .about , .resume").hide();
    $("#about").click(function(e)
    {
        e.preventDefault;
        $(this).find('li').toggleClass('active ');
        $(".about").slideToggle("slow");

    });

    $("#resume").click(function(e)
    {
        e.preventDefault;
        $(this).find('li').toggleClass('active');
        $(".output .resume").slideToggle("slow");

    });
});

<div class="cont2">
    <ul>
        <a href="#" id="about"><li class="fade-in one " >About</li></a>
        <a href="#" id="resume"><li class="fade-in two">Resume</li></a>
        <a href="#"><li class="fade-in three">Portfolio</li></a>
        <a href="#"><li class="fade-in four">Contact</li></a>
    </ul>
</div>

<div class="output">
    <div class="about">
        <p>About</p>
    </div>

    <div class="resume">
        <p>Resume</p>
    </div>
</div>

EDIT : Updated code:

$(document).ready(function(){

    $(".cont1").hide();
    $(".cont1").fadeIn(1000);
    $(".output .about , .resume").hide();
    $("#about").click(function(e)
    {
        e.preventDefault();
        $(".cont2 li .active").removeClass('active');

        $(this).find('li').toggleClass('active');
        $(".about").slideToggle("slow");
        $(".resume").slideUp("slow");

    });

    $("#resume").click(function(e)
    {
        e.preventDefault;
        $(this).find('li').toggleClass('active');
        $(".output .resume").slideToggle("slow");

    });
});

Answer №1

In my opinion, it would be more efficient to use a single click event for all the links on your page. This way, you can avoid duplicating code unnecessarily. Simply utilize the id attribute of your anchor and associate it with the corresponding divs class that shares the same name. Since this structure already exists in your HTML, there is no need to make any changes.

Additionally, if you want the transition effect when hiding elements using slideUp to be more noticeable, consider triggering the slideDown (show) effect within its callback function. Essentially, you should wait for one animation to finish before initiating the next one.

Here's a revised version of the script:

$(".output .about , .resume").hide();

$("a").click(function (e) {
    e.preventDefault();

    var hiddenDiv = $(".output ." + $(this).attr("id"));
    var visibleDiv = $(".output > div:visible");

    // Show desired div if all others are hidden
    if (visibleDiv.is(":visible")) {
        visibleDiv.slideUp("slow", function () {
            hiddenDiv.slideDown("slow");
        });
    } else {
        hiddenDiv.slideDown("slow");
    }
});

You can view the live demo here: http://jsfiddle.net/4cvnrh51/

Answer №2

Locate all elements with the active class and remove it:

$(document).ready(function(){

  $(".output .about , .resume").hide();
  $("#about").click(function(e)
  {
    e.preventDefault();
    $(this).find('li').toggleClass('active');
    $(this).siblings().find(".active").removeClass('active');
    $(".about").slideToggle("slow");
    $(".resume, .portfolio, .contact").slideUp("slow");

  });

  $("#resume").click(function(e)
  {
    e.preventDefault();
    $(this).find('li').toggleClass('active');
    $(this).siblings().find(".active").removeClass('active');
    $(".resume").slideToggle("slow");
    $(".about, .portfolio, .contact").slideUp("slow");
  });
});

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

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

Ways to enhance a browser's response with soup

I have a script that sends multiple requests to a website using RoboBrowser and retrieves responses, but now I need to filter these responses to exclude any containing the phrase "Case Status Not Available". I attempted to use Beautiful Soup for this purpo ...

necessitated in specified input with assigned value

Here is some code I have: <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <select required> <option value=1>Volvo</option> <option value=2>Saab</option> <option value=3>Merc ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Generating alternate list items

I'm attempting to design a list style that resembles the one depicted in the image linked below: https://i.stack.imgur.com/U7vMw.jpg My issue is that when I try to add borders, they end up applying to the entire structure. .styled-list { list-st ...

What can I do to enhance the responsiveness of this rotating cube?

Here I am working with a rotating cube on the web. Check out my similar code. I am attempting to make it so that when the browser size is reduced, the table and cube also shrink in size accordingly without changing their position relative to each other. I ...

Stop automatic resizing on mobile device after postback

Encountered an issue with a website I'm currently developing. It's not causing any problems, but I want to enhance the user experience. My aim is to maintain the zoom levels of mobile devices after a postback. To provide more context, there is a ...

Creating a new web application, I require a loading overlay to appear during transitions between pages

I've checked high and low, but I can't seem to find the solution! My webapp has a page that is bogged down with data causing it to load slowly. Is there a way to display a loading div while transitioning to the next page? Perhaps something like ...

AmCharts Axis renderer mistakenly renders an additional grid line

I have successfully created a basic XYChart using amcharts4. To get rid of the grid lines on the x-axis, I changed the stroke opacity for the x-axis grid to 0 using the following code: xAxis.renderer.grid.template.strokeOpacity = 0; Everything was workin ...

Tips for managing responsive font sizes as screen size decreases

Hey there, I could really use some assistance with a new website I've been working on. While I have experience building Joomla sites for the past 6 months, this is my first attempt at making a responsive site using media queries. You can check out th ...

What could be causing the event listener to not be triggered?

I'm having an issue with a simple code that is supposed to display an alert box when a hyperlink is clicked, but it's not working. I believe the script is not being called. Can someone help me figure out what's wrong? Here is the HTML code: ...

Entering credit card information in a modal popup using Bootstrap form

I have implemented a bootstrap modal for my credit card payment form and now I want to validate the credit card information. Currently, I am using basic validation in jQuery. <script> $(function() { $('#error_message_reg').text(""); //$( " ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Improved efficiency in CSS for left transition animations

Here is the current code I am using: .s2 { top: 150px; left: 20px; position: absolute; transition: left 300ms linear; } I am currently updating the left position dynamically using JavaScript based on scroll events. However, I have noticed that th ...

Are the dimensions of <TD> and <table> not displaying properly?

I've encountered a peculiar issue that I need help with. Here is the Fiddle link: http://jsfiddle.net/H3W4X/ If you want to view it in fullscreen: http://jsfiddle.net/H3W4X/embedded/result/ This is the code snippet causing trouble: <div id="wor ...

Unable to retrieve post data during AJAX insertion in CodeIgniter

I am using ajax to send data to my Codeigniter controller from an external JS file. Below is the ajax code snippet I am using: $.ajax({ url: 'http://localhost/test/testController/testFunction/', ...

Obtain the dropdown menu links for every row in a table using Python3 along with Selenium

Seeking assistance as a beginner in Python, I am attempting to automate the downloading process of old newspaper archives from a specific website () using the script provided below. Despite my efforts, I have encountered difficulty in getting the script t ...

Set the default value for a form control in a select dropdown using Angular

I've been struggling to figure out how to mark an option as selected in my select element, but I haven't had any luck. I've tried multiple solutions from the internet, but none of them seem to be working for me. Does anyone out there have ...

Tips for splitting a container of specific height into sections measuring 80% and 20%

I am working on a container with a fixed position that I want to split into two halves: 80% and 20% at the bottom. This is what I want it to look like: Click here to see the image. Note: The layout should adjust itself when the window is resized. You c ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...