What is the best way to manage the gradual disappearance of multiple divs belonging to the same class using jQuery?

I need help with a hover effect for 6 divs on a page. Each div has a layer on top that fades out on hover and fades back in on mouseleave. I currently have code for each individual div layer, but it's causing a stack overrun. How can I assign this functionality to all six top layers in just one block of code? Any guidance would be appreciated! Check out the JSFiddle here

<script>
    $(function(){      
        $(".hover6").mouseenter(function() {
            $(this).siblings().fadeIn();
            $(this).fadeOut();
        });

        $("#div6").mouseleave(function() {
            $(".hover6").fadeIn('slow');
        });
        $(this).siblings().fadeOut();
    })  
</script>



<script>
    $(function(){      
        $(".hover5").mouseenter(function() {
            $(this).siblings().fadeIn();
            $(this).fadeOut();
        });

        $("#div5").mouseleave(function() {
            $(".hover5").fadeIn('slow');
        });
        $(this).siblings().fadeOut();
    })    
</script>

//and so on - identical script for other 4 divs

Answer №1

Employ a shared class to simplify event binding.

HTML

<div id="div1" class="divContainer">
    <div class='hover hover1'>Overlay on top</div>
    <div>subdiv in div 1</div>
    <div>subdiv in div 1</div>
</div>

Script

//Event binding using shared class
$(".hover").mouseenter(function () {
    $(this).siblings().fadeIn();
    $(this).fadeOut();
});

$(".divContainer").mouseleave(function () {
    //Utilize find 
    var hoverElem = $(this).find(".hover");

    hoverElem.fadeIn('slow'); 
    hoverElem.siblings().fadeOut();     
});

DEMO

Answer №2

<div class="container">

  <div id="block1" class="hover-effect">
    <div>Overlay on top</div>
    <div>subdivision in block 1</div>
    <div>subdivision in block 1</div>
  </div>

  <div id="block2" class="hover-effect">
    <p class="custom-style1">This is block 2</p>
    <div>Overlay on top</div>
    <div>subdivision in block 2</div>
    <div>subdivision in block 2</div>
  </div>

  <div id="block3" class="hover-effect">
    <div>Overlay on top</div>
    <div>subdivision in block 3</div>
    <div>subdivision in block 3</div>
  </div>

  <div id="block4" class="hover-effect">
    <div>Overlay on top</div>
    <div>subdivision in block 4</div>
    <div>subdivision in block 4</div>
  </div>

  <div id="block5" class="hover-effect">
    <div>Overlay on top</div>
    <div>subdivision in block 5</div>
    <div>subdivision in block 5</div>
  </div>

  <div id="block6" class="hover-effect">
    <div>Overlay on top</div>
    <div>subdivision in block 6</div>
    <div>subdivision in block 6</div>
  </div>
</div>

$('.hover-effect').click(
  function() {
    $(this).animate({'width': '100%', 'height': '100%'}, 600).siblings().animate({'width': '0', 'height': '0'}, 600);
    $('<button class="close">Close</button>').appendTo('.container');
  });

$(document).on('click', '.close', function() {
  $(this).animate({
    'width': '0',
    'height': '0'
  }, 600).siblings().animate({
    'width': '50%',
    'height': '33.33%'
  }, 600);
  $(this).remove();
});

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

Switching from the jQuery .it() function to the Angular framework

I am looking to convert this code to Angular. I have already written some of the code, but I am unsure what to use in place of :It(). The jQuery code can be found at the following URL: jsfiddle.net Here is my Angular code: x = 3; $scope.itemsPerPage = 3; ...

Issue encountered while rendering tables with Jquery-dataTables

Encountering an issue with jquery datatables when fetching data from a URL using ajax calls. Implementing the codeigniter framework, I utilize the datatables library to create datatable objects by invoking the echo $this->datatables->generate() metho ...

I'm curious about something I noticed in an HTML example within the text content section of elements. Can you help clarify this for me?

I recently came across a repository that was part of a bootcamp curriculum for learning full stack development. In one of the lessons on jQuery, students were tasked with building a calculator. However, I noticed some strange variables in the HTML where te ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

What is the best way to make my navbar adjust seamlessly to accommodate the largest element?

Currently, I'm facing an issue where my logo is not fitting properly inside my navbar and it's "falling out." You can see the problem here: https://i.sstatic.net/l4T1B.png Here is the relevant code: HTML: <nav class="container-fluid navbar ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...

Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute. For example: [{ { "orderNo":"1", "description":"Item 1", "note": "Note 1" }, { "orderNo":"2", "description":"Item 2", ...

ReactJS: Dealing with issues in setting a dynamic index for the setState key

I have been attempting to utilize setState within a for loop using index in the following manner: for (var i = 0; i <= 9; i++) { this.setState({ location_option[i]: resourceData.location_option+i, location_option[i]_type: resourceData.locatio ...

Challenges Encountered When Loading JQuery DataTable with JSON Data in MVC Framework by Clicking a Button

On my MVC page, I have a JQuery DataTable that needs to be populated when the user clicks the Query Button. This is the structure of my DataTable: <table id="mytable" class="table table-striped table-bordered mt-5"> <thead> <tr> ...

Is there a way to achieve a flex layout without having to modify the HTML structure?

I am working on achieving a specific layout using CSS: https://i.stack.imgur.com/xg7ZA.png This is the HTML structure I have and it cannot be altered, along with what I have managed to add with CSS. It's almost there but missing something: .conta ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Install the following packages using npm: tailwindcss, postcss, autoprefixer, error, and next

npm ERR! code ERESOLVE npm ERR! ERESOLVE could not find a solution to the problem npm ERR! npm ERR! While trying to resolve: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/react npm ERR! requires react@">=16.8 ...

Switch up the font style of the title element

Is it possible to modify the font-family of the title attribute in an input field using either JavaScript or jQuery? <input type="text" title="Enter Your Name" id="txtName" /> ...

Developing a realtime search feature using AJAX and CodeIgniter

Attempting to implement a live search feature in CodeIgniter for the first time. As a newcomer to web development, still in the learning process. Came across a tutorial on how to achieve this here. Struggling with adapting the code from the tutorial to fi ...

Trouble encountered with updating the Input value upon pressing the enter key

In my ReactJS-based application, I am working on a component that includes a Material Input element. Users can enter words and when they press the enter key, those words are displayed as chips within the same input field. The issue I'm encountering i ...

What is the best way to include CSS in a CodeIgniter project?

I am facing an issue with loading a CSS file in Codeigniter. It seems like there might be something wrong with my code. Can someone help me understand how to properly load a CSS file in Codeigniter and possibly identify any errors in my current code? < ...

Creating header menus with section labels in Windows 8 Metro can be easily accomplished by utilizing Javascript

Is there a way to create a navigation menu in Windows 8 Metro JavaScript that includes header menus and section labels, similar to the example shown below? ...

What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error: url is pointing to root url has a slug throw err; // Rethrow non-MySQ ...

Check to see if a div element with an id that contains a numerical value has been

My HTML code contains X elements, each with an ID in the format: viewer_mX In this case, X is a number ranging from 1 to m (where m varies). I am looking to utilize JavaScript to retrieve the respective element's number X when a user clicks on one ...