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

Tips for showing a single table with buttons on display

I am using R markdown and have included multiple tables with buttons, but when I open the file, all tables are displayed at once. How can I ensure only one table is shown upon opening the file? <script type="text/javascript"> function sh ...

Ways to enhance multiple ng-repeats efficiently with css grid

Looking to create a CSS grid table with 5 columns and an undetermined number of rows. The goal is to display a pop-up element when an element in the first column is clicked, covering columns 2 through 5. This ensures that only the first column remains visi ...

What is the best way to transfer the array from my function and have it returned?

I've been struggling to successfully pass my array to an external function. Can anyone help me with this? You can find the code that I'm working on in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output. The expected result should be passe ...

Is it possible to create an input field exclusively for tags using only CSS?

I am currently facing some limitations with a website I am managing. Unfortunately, I do not have the ability to incorporate additional libraries such as custom jQuery or JavaScript scripts. My goal is to customize an input field for tags so that when us ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

The jQuery navbar's active class fails to function properly when an href is added

I'm facing a puzzling situation. I created a navbar using jQuery Mobile following the instructions on their official website: jQuery Mobile Navbar Demos Everything functions smoothly until I introduce href attributes in the list elements within the u ...

Click to make the arrow come to life through animation!

I am brand new to coding and this is my inaugural code snippet: .container_menu { position: relative; top: 0px; left: 0px; width: 25px; height: 25px; } .container_menu .line-1 { background-color: black; width: 59%; height: 2px; positio ...

Determine the 'source' attribute value of the image (img) with a dynamically changing Id

Below is the code snippet: <img id="simple_captcha-ad089ff4819" src="/simple_captcha?code=a35401d"> The id of the above img tag changes constantly with each new action. For example, the next id could be "simple_captcha-sfw454sdfs". Therefore, I n ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Omitting a portion of the key in JSON request with jQuery

Currently, I am populating some elements using JSON data. However, when a new JSON is loaded, the structure of the JSON appears slightly different. How can I ignore the initial part of the key to make it work? I thought about using an asterisk but that res ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Excessive text in HTML div element

Whenever I maximize the window in any browser, I type a long string in a div or span tag. It perfectly fits within the div tag. However, when I minimize or compress the browser width, the text spills out of the div area. I am looking for a solution to set ...

Creating responsive images in Bootstrap columns

I've found a solution to my issue with large images, but I am still struggling with smaller images not fitting well into larger spaces. Essentially, I created a CMS for a user who required templates with various bootstrap columns as content areas. Cu ...

Determining the pageY value of a div element with overflow-y styling

Currently, I have implemented a script that tracks the mouse's position upon hover. My goal is to integrate this script within a div that has overflow-y: scroll The script currently utilizes pageY which identifies the position relative to the windo ...

I'm using SASS in my project, can you provide guidance on customizing the UI with @aws-amplify/ui

I've recently taken over a Next.js (React) project from another developer and they've used .scss files (SASS) for styling. The specific project I'm working on can be found here https://github.com/codebushi/nextjs-starter-dimension My task n ...

Challenging jQuery AJAX journey

After tirelessly searching the web, I am still unable to solve this issue and cannot understand why it is not functioning. My JavaScript code seems to work only on Firefox and fails to run on any other browser. So, I have made the decision to switch to j ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

What is the best way to incorporate two range sliders on a single webpage?

I recently started using rangeslider.js on my webpage. I wanted to convert two input fields into range sliders, so I began by converting one successfully. Initially, the HTML code looked like this: <div class="rangeslider-wrap"> <input type=" ...

Achieving effective targeting of the second segment within a string enclosed in a span tag through increased specificity

When it comes to styling elements, the easiest way is to use classes and assign the properties needed. However, 1. I'm not a huge fan of creating classes all over the place. That's what specificity and CSS mapping are for. 2. Going thro ...