Animate hovering over a specific element within a group of similar elements using jQuery

Hi there! I recently started exploring Js and jQuery, and I was able to create a cool width change animation on a div when hovering over another. However, I ran into an issue when trying to implement this with multiple sets of similar divs. Whenever I hover over one div, the action triggers on all the others as well. I've tried using "this" and "next()" but it only made things worse. Can someone please shed some light on this for me? Thank you!

Here is my code snippet:

https://jsfiddle.net/HiD3f/LmbaL1qo/2/

<html>
   <div class="mapHideBtn collapsed"></div>
   <div class="searchBlock hidden"></div>

   <div class="mapHideBtn collapsed"></div>
   <div class="searchBlock hidden"></div>

   <div class="mapHideBtn collapsed"></div>
   <div class="searchBlock hidden"></div>
</html>

<style>
  .searchBlock {
     display : inline-block;
     height: 50px;
     background : red;  
  }
  .hidden {
     width: 0; 
     transition : width 0.4s ease-in
  }
  .shown {
     width: 300px;
     transition : width 0.4s ease-in
  }
  .mapHideBtn {
     display : inline-block;
     width: 50px;
     height: 50px;
     background : green;
  }
</style>

<script>
  $('.mapHideBtn').hover(function(){
      if($(this).hasClass("collapsed")) {
        $('.searchBlock').removeClass("hidden").addClass("shown");
        $('.mapHideBtn').removeClass("collapsed").addClass("expanded");
      } 
      else {
         $('.searchBlock').removeClass("shown").addClass("hidden");
         $('.mapHideBtn').removeClass("expanded").addClass("collapsed");
      };
  });
  

Answer №1

To achieve this effect, you can utilize the $(this).next() function along with toggleClass(). Check out this DEMO for a visual representation.

$('.mapHideBtn').hover(function(){
  $(this).next().toggleClass('shown');
});

Update: If you want the red bar to remain open when hovered over, consider using a pure CSS solution like demonstrated in this DEMO, or alternatively, place .searchBlock inside .mapHideBtn as shown in this DEMO.

Answer №2

To resolve your issue, make sure to update your jQuery selectors to utilize $(this) and $(this).next().

It seems like you are encountering a situation where a loop is targeting all the specified selectors and applying the defined rules to each of them.

For a corrected version, refer to this updated fiddle: https://jsfiddle.net/LmbaL1qo/9/

Here's the revised code snippet:

$('.mapHideBtn').hover(function() {
  if ($(this).hasClass("collapsed")) {
    $(this).next().removeClass("hidden").addClass("shown");
    $(this).removeClass("collapsed").addClass("expanded");
  } else {
    $(this).next.removeClass("shown").addClass("hidden");
    $(this).removeClass("expanded").addClass("collapsed");
  };
});

Answer №3

Here is a straightforward solution:

<script>
    $('.mapHideBtn').hover(function(){
    if ($(this).hasClass("collapsed")) {
        $(this).next().removeClass("hidden").addClass("shown");
        $('.mapHideBtn').removeClass("collapsed").addClass("expanded");
    } 

    else {
        $('.searchBlock').removeClass("shown").addClass("hidden");
        $('.mapHideBtn').removeClass("expanded").addClass("collapsed");
    }
});
</script>

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 is the reason for Nightwatch running each .js file as a Child process? Could it be due to alterations in the configuration settings

Recently, I've been experiencing an issue when running Nightwatch.js where my console is spawning child processes for every .js file in each folder and subfolder. Multiple Chrome instances are opening along with them and even the module folders with r ...

In a multidimensional array, locate the key corresponding to the specified value

I am facing an issue with my code that involves an array containing various fruits with product ID and price as keys for different values. While I am able to retrieve the correct price, I am struggling to get the name of the chosen product. For instance, ...

Problem with transitioning to a different page on Next.js

I am having trouble navigating to a different page in Next.js using the router.push function. The goal is to route to "example.js" by utilizing a variable called ChangePage, which leads to a single div element on that page. However, despite following the ...

What is the reason behind using angle brackets to access the initial value of an array with a variable inside?

I've been experimenting with this technique several times, but I still can't quite grasp why it works and haven't been able to find an answer. Can someone please explain? let myArray = [0, 1] let [myVar] = myArray console.log(myVar) // outpu ...

Prevent the sender from receiving notifications from Firestore

Data is transmitted to firestore by the sender firestore saves the data firestore shares the data with all connected clients, sender included Is there a method for the sender to not receive the notification? OR If the sender does get the notification, is ...

Use $.ajax to display the menu by capturing an array of elements {0}

Whenever I click on one of the DIV elements, a menu pops out on the side displaying more information about the clicked element. I can determine which element I'm clicking on, but I'm struggling to pass that information from jQuery to the PHP pag ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Informa ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Element sticking and bouncing

I'm currently facing an issue with Sticky-kit where one of my elements jumps when it reaches the bottom of its parent div. Below is the code snippet: <div class="wrapper"> <div id="bg"> <div id="text"> Lorem ipsum dolor sit a ...

Achieving a centered Title while aligning Nav all the way to the right using flexbox: tips and tricks

I am currently using flexbox to align the h1 and nav on the same line with display:flex. I want the title to be centered and the navigation to be on the right side. However, I am struggling to figure out how to move the navigation all the way to the right. ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wo ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...

Animating Angular for particular conditions

My goal is to create unique animations for specific state changes in my AngularJS app. I found inspiration from this tutorial: https://scotch.io/tutorials/animating-angularjs-apps-ngview, which works well. However, I am aiming for the following animations: ...

Eliminate any excess space to the right of the image

Utilizing Bootstrap alongside React, I've encountered an issue with images causing unwanted whitespace to the right. I've thoroughly examined the elements but have been unable to resolve this issue. Despite researching Bootstrap Col online, the ...

Comparing attribute selectors to class selectors in the realm of styling

I often come across code that looks like this: <input type="text" class="class1" name="text"> <input type="submit" class="class2" name="submit"> which is then styled as follows: input[type=text] { styles here...} input[type=submit] { sty ...

Conceal a particular row in SharePoint by utilizing JavaScript with jQuery

I'm facing an issue with SharePoint 2010 where the _cts folder is visible in all document libraries. Despite my efforts to research and find a solution, I have been unsuccessful so far. For now, my workaround is to hide the entire row. Here's a ...

What is the best way to incorporate jQuery's default handsontable into an AngularJS directive?

I currently have a handsontable functioning in a non-AngularJS application, and I am in the process of developing a new version of the software that heavily utilizes AngularJS (SPA). My question is: is it possible to encapsulate the existing handsontable ...

How does SWR affect React state changes and component re-rendering?

I am currently utilizing SWR for data fetching as outlined in the documentation: function App () { const [pageIndex, setPageIndex] = useState(0); // The API URL incorporates the page index, which is a React state. const { data } = useSWR(`/api/data? ...

Instead of stacking neatly, the Bootstrap rows are overlapping each other

I am currently working on a webpage design using bootstrap. The layout consists of different sections, each containing a bootstrap row within a container. However, I encountered an issue where new rows are not appearing below the previous row as expected, ...

Detecting duplicate key values within a JSON array using Angular.js

I am seeking a solution in Angular.js to verify if duplicate key values exist within a JSON array. Below is a breakdown of my code: var result=[{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8dac8b ...