Tips for switching "a" tag elements to reveal concealed DIVs in a similar way to the Facebook notification center

I have a situation in my code where I need to toggle between two a elements to display a hidden div with content one at a time. This functionality is similar to how the Facebook notification center works when you click on the icons, which I'm sure most of you have encountered on the top left corner near the logo on the Facebook website. How does that mechanism actually work?

Below is the code snippet I am working with:


<style>
div, a {
    display: block;
}

body {
    width: 500px;
    margin: 100px auto;
}

a {
    border: 1px solid #ccc;  
    background: #ececec;  
    -webkit-border-radius: 3px;  
    padding: 5px 20px;  
    text-align: center;
    color: red;
    text-decoration: none;
}

#one {
    margin-bottom: 30px;
}

.dn_js {
    display: none;
}

.db_js {
    display: block;
}
</style>

Here is the HTML structure:


<div class="wrap">
<div id="one">
    <a href="#" data-open="frdz" class="aTggl active">Friends</a>
    <div id="frdz" class="innerWrap dn_js">Mike</div>
</div>
<div id="two">
    <a href="#" data-open="Ntfn" class="aTggl">Notifications</a>
    <div id="Ntfn" class="innerWrap dn_js">Peter</div>
</div>
</div>

And here is the jQuery code used for toggling the elements:


<script type="text/javascript">
$(document).ready(function (e) {
    $(".aTggl").on("click", function(e) {
        e.preventDefault();
        var $this = $(this);

        $(".active").removeClass("active");

        $this.addClass("active").parent().siblings().children(".innerWrap").addClass("dn_js");

        var content_show = $(this).data("open");
        $("#" + content_show).addClass("db_js"); 
    });
});
</script>

Answer №1

As pointed out by mg007, it is recommended to use toggle() and toggleClass() instead.

Check out the Fiddle: http://jsfiddle.net/dASdJ/2/

var switchToggle = function (toggleEle) {
    $('#' + $(toggleEle).data('open')).toggle('slow', function() {
        // Animation complete.
          $(this).parent().children('.aTggl').toggleClass('active');
    });
 }

$('.aTggl').click(function(e) {
    e.preventDefault();
    switchToggle($(this));

    if (!$(this).hasClass('active')) {
        $('.active').each(function() {
          switchToggle($(this));
        });
    }
});

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

What could be the reason for the "category empty" message appearing at the first index after clicking on the add

When I click on the add products button, why is the category name empty at the first index? 1. The text starts from index 2 of the category column. 2. When I change the value from the dropdown, it first displays the previous value in the category column an ...

"Endowed with improper dimensions, the BootStrap collapse feature

Yesterday, I posted about an issue with BootStrap and panel collapsables causing graph sizes to become distorted. The post was locked because there was no accompanying code. I have now created a code snippet for you all to see the exact problem I am facing ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

What is the process of choosing a language (English/French) within a pop-up?

<body style="text-align:center"> <h2>Popup</h2> <div class="popup" onclick="myFunction()">Interact with me to show/hide the popup! <span class="popuptext" id="myPopup">A Simple Popup!</span> </div> <script& ...

Using the power of Selenium's XPath, we can easily navigate through a table to access

Looking for assistance in creating selenium xpath for the various column links within a table. Each row has a unique identifier and contains information about a product, including the name. Based on the product name, I need to locate other links within the ...

What is the best way to extract the chosen value from a dropdown menu within the $_POST array?

In my HTML code, I have a droplist using the <select> tag. How can I retrieve the selected value from the $_POST array once the user submits the form? <form action="subj_exec.php"> <?php echo $_SESSION['SESS_MEMBER ...

Retrieve information from the input field and then, upon clicking the submit button, display the data in the

When a user inputs their name, email, subject, text, and telephone number, I want to send an email with that data. The email will be sent to a specific email address, such as [email protected]. This process is crucial for a hotel website, where the em ...

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

What is the reasoning behind excluding any JavaScript code between the <script> tags when our intention is solely to incorporate an external JS file?

It's puzzling to me why the author of the "Javascript & Jquery: the missing manual , second edition" recommends the following sentence: When including the src attribute to connect to an external JavaScript file, avoid placing any JavaScript cod ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: I want to create a feature where selecting a month will aut ...

Symfony2 - Utilizing an Entity repository to encode data into JSON for efficient AJAX calls

I'm currently working on implementing a dynamic text field with AJAX autocomplete functionality. In order to handle the AJAX call, I have created a method in the controller. public function cityAction(Request $request) { $repository = $this-> ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...

What is the best way to incorporate a fadeIn effect while using the .attr method?

I am working with a line of code that switches between classes class1 and class4 to update the background of my website. I would like to incorporate a fadeIn effect each time the class changes. Can you help me with this? Thank you! Below is the code snipp ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

Is there a way to use JQuery to make one button trigger distinct actions in two different divs?

For instance: Press a button - one div flies off the screen while another div flies in. Press the button again - Same div flies out, other div returns. I'm completely new to Javascript/JQuery so any assistance would be highly appreciated! Thank you ...

How to create a jQuery image slider without specifying a fixed width?

Recently, I tried using the coin slider on my application, but unfortunately, it seems to be limited by the width of the image. I'm looking for a jQuery image slider that can adapt to different screen sizes, like 1280*768 and 800*600. Does anyone know ...

designing a presentation with customizable durations for each slide

I am trying to implement a slideshow using the slides.js jquery plugin and I have a specific requirement for the duration of each slide. My goal is to have the first slide, which contains an embedded video, display for 7 seconds, while the subsequent slid ...

What steps are involved in merging Webflow code with an Angular web application?

As a newcomer to web development with Angular, I have the source code of a website already developed with Angular and I want to customize it to suit my needs. My issue is that when I add generated code from Webflow to an existing partial page, the browser ...

Filtering, cleaning, and confirming the validity of data input allowed for HTML tags

While there is a lot of information available on sanitizing, filtering, and validating forms for simple inputs like email addresses, phone numbers, and addresses, the security of your application ultimately relies on its weakest link. What if your form inc ...