Fading Out with JQuery

My page contains about 30 same-sized divs with different classes, such as:

.mosaic-block, .events, .exhibitions, .gallery, .sponsors, .hospitality, .workshops, .lectures {
    background:rgba(0, 0, 0, .30);
    float:left;
    position:relative;
    overflow:hidden;
    width:6.36896%;
    height:22.2287%;
    margin:2px;
} 

There is also a navi class:

<div id="navi">
    <a href="#"><div id="t0" class="n0 lfloat"><img src="images/home.png"><span>Home</span></div></a>
    <a href="#"><div id="t1" class="n1 lfloat"><img src="images/events.png"><span>Events</span></div></a>
    <a href="#"><div id="t2" class="n2 lfloat"><img src="images/workshops.png"><span>Workshops</span></div></a>
    <a href="#"><div id="t3" class="n3 lfloat"><img src="images/lectures.png"><span>Lectures</span></div></a>
    <a href="#"><div id="t4" class="n4 lfloat"><img src="images/exhibitions.png"><span>Exhibitions</span></div></a>
    <a href="#"><div id="t5" class="n5 lfloat"><img src="images/hospitality.png"><span>Hospitality</span></div></a>
    <a href="#"><div id="t6" class="n6 lfloat"><img src="images/gallery.png"><span>Gallery</span></div></a>
    <a href="#"><div id="t7" class="n7 lfloat"><img src="images/sponsors.png"><span>Sponsors</span></div></a>
</div>

When a user clicks on "Events" [div #t1], all boxes except those with the class .events should fade out. This functionality is implemented using JQuery. However, the code seems too lengthy. Is there a way to shorten it?

    <script type="text/javascript">
    $(function () {
    $('a #t0').click(function() {
        $("*").animate({ 
            opacity: 1.0
            }, 500 );

        });

    $('a #t1').click(function() {
        $("#t1").toggleClass("active");
        $(".exhibitions, .workshops, .sponsors, .hospitality, .lectures, .gallery").animate({ 
            opacity: 0.0
            }, 500 );
        $(".events").animate({ 
            opacity: 1.0
            }, 500 );

        });
</script>

The code for #t2, #t3, #t4 can be similar. How can I make this more concise?

EDIT#1

Do I need to write .click(function() 7 times for each #t individually and exclude that class when writing $(".exhibitions, .workshops, .sponsors, .hospitality, .lectures, .gallery").animate()? Also, how can I remove the active class when the user selects another option?

Answer №1

Here is a suggestion for you to try out: Live Demo

To make this work, ensure that all boxes have a common class, in this case, I chose to use boxes.

This code snippet also manages the "Home" option by displaying all the divs and setting the clicked div class to active.

<script type="text/javascript">
    $(function () {
        $('a #t0').click(function() {
            $(".boxes").animate({ 
                opacity: 1.0
                }, 500 );

        });


        $("#navi a").click(function() {
            c = $(this).text().toLowerCase();

            if(c != "home") {
                $('.' + c).animate({ 
                   opacity: 1.0
                 }, 500 );
                $('.boxes').not('.' + c).animate({ 
                   opacity: 0.0
                 }, 500 );

                $(".active").removeClass('active');
                d = $(this).find('div')[0];
                $(d).addClass('active');
            }
        });
    });
</script>

Answer №2

To achieve the desired effect, consider employing jQuery's fadeOut and fadeIn functions. To target elements without the events class, utilize the CSS not selector as follows: not(.events)

Answer №3

To start, it would be helpful to improve the identifiers in your main menu for easier navigation:

<a href="#" id="home">....</a>
<a href="#" id="events">....</a>
<!-- etc -->

Without a clear picture of how the content divisions are structured, let's assume they follow this format (using the content class to manage non-selected content):

<div class="home content">...</div>
<div class="events content">...</div>
<!-- etc -->

To simplify your JavaScript code, consider using fadeIn() and fadeOut() for transitions, addClass() and removeClass() for class manipulation, and consolidate event handling with a single click event listener for all links.

$('#navi a').click(function() {

    // only execute if clicked anchor is not active
    if (! $(this).hasClass('active')) 
    {
        // managing active class state
        $('#navi a').removeClass('active'); // remove class from all anchors
        $(this).addClass('active');         // add class to selected anchor

        // fading out / in required content
        var showContentByClass = '.' + $(this).attr('id');
        $('.content').not(showContentByClass).fadeOut('slow');
        $(showContentByClass).fadeIn('slow');
    }
});

This updated script includes a check to ensure the chosen option is different from the currently displayed content.

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

Transitioning the implicit width

Using implicit width, which involves adding padding to an element containing text to give the parent container a specific but unstated width, can be quite elegant. However, it poses challenges when it comes to transitions. Is there a way to achieve a trans ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Select either one checkbox out of two available options

My form includes two checkboxes, allowing users to click on both of them. I'm wondering if it's possible to set it up so that only one checkbox can be selected at a time. For example, clicking on the first checkbox would turn it on while turning ...

At what point does the cleanup function in UseEffect activate the clearInterval() function?

In the process of creating a timer for a Tenzie game, there is an onClick function that changes the state of isTimerActive from false to true when a user clicks a button. The initial value of tenzie state is also set to false, but once the user completes t ...

What is the reason behind the immediate firing of the animate callback function when a CSS transition is present?

I am facing an issue where the callback function fires immediately, disregarding the linear ease type and defaulting to the swing ease in CSS transitions. Is there a way to ensure that the animate function works correctly with the transition? The reason fo ...

The Vue JS task manager is unable to remove completed tasks from the list

I'm encountering an issue with the 'DELETE ONLY FINISHED' button. The goal is for this button to delete all finished tasks. When a task is completed, its 'finishedTask' property changes to true. I have attempted to store all finish ...

Verifying unloaded images

I am new to using Selenium and I need help. I am attempting to retrieve all the image sources on a page in order to identify any images that have not loaded. How can I check the image sources? Can I use "null" as a check? Below is my code, which contains m ...

Exploring depths of data with AngularJS: multiple levels of drilling

I am new to AngularJs and facing a challenge with a complex JSON structure that I need to use for an auto complete feature. I want to create an auto complete for only the child elements within the structure, without displaying the parent categories. Acce ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Deactivating all HTML DOM elements except for those with a specific #id

Currently, my goal is to deactivate all elements on an html page while keeping certain elements active. $('body').find('*').attr('onclick',"return false;"); //Deactivating all elements // I am attempting to activate the eleme ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

Error encountered when generating bower.json due to absence of version number

After generating the bower.json file, I noticed that the version number was not included in the information collected. The current content is as follows: { "Name": "conFusion", "Authors": [ "Aurora" ], ... } Although the version n ...

Guide to create a sliding menu transition from the viewport to the header

I am just starting to learn jQuery and I want to create a menu similar to the one on this website Specifically, I would like the menu to slide down from the viewport to the header, as shown in the template in the link. I have searched through the jQuery ...

Incorporating docsify CSS styling into Markdown within the VScode environment

When it comes to building my blog, I've decided to go with docsify and manage my markdown files using VScode. I wanted a preview of my blog, and after noticing that <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify@4/lib/t ...

Enhancing ajax content with Rx.Observable.fromEvent: A step-by-step guide

I am currently fetching content using Ajax, in the form of a json object, which is then displayed in the browser. var stateSubjectSub = stateSubject.subscribe(function(data) { console.log('state changes'); console.log(data); var list = document ...

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

What is the best way to execute the .playVideo() function in Youtube using jQuery?

Is it possible to embed a YouTube video and have it play immediately upon clicking using jQuery? I'm having trouble figuring out how to implement this with the live click function. Any suggestions? var youTubeVideo = '<object width="370" heig ...

What is the best way to utilize a color picker to apply CSS color to a parent element?

When the pencil glyphicon is clicked, a color picker appears. I only want to apply the selected color from the color picker to the list elements that are the grand parent of the pencil glyphicon. Here's a snippet of my Ruby front-end code: <% cat ...