Fade in only a single element from a specific class using Jquery

I recently attempted to create a script that would fade in a tooltip when hovering over a link or image. Everything was working fine except for the fact that only one tooltip would appear at a time. In other words, I wanted to hover over an image and have a tooltip display directly above it without any other tooltips on the page being visible. I understand why this is happening (all tooltips have the same class, so hovering over any image fades them all in), but I'm unsure how to fix it. I hope I've explained my issue clearly and would greatly appreciate any help. (Please forgive me if my English isn't perfect, it's not my native language)

Here is the code snippet:

$(function() {
$('.button').hover(function() { 
    $('.tooltip').stop().fadeTo("fast", 0.8); 
}, function() { 
    $('.tooltip').fadeTo("fast", 0.0); 
});
});
.wrapper{
    width:90px;
    margin:auto;
    margin-top:10%;
}

.tooltip{
    margin-left: auto;
    margin-right:auto;
    background-color:#34495e;
    color:white;
    border-radius:5px;
    opacity:0.8;
    padding:5px;
    text-align: center;
    font-size:15px;
    font-family: 'Open Sans', sans-serif;
    display: block;
    opacity:0.0;
}

.button img{
    margin-top:5px;
    height:50px;
    width: 50px;
    display:block;
    margin-left:auto;
    margin-right:auto;
}

.button img:hover{
    cursor:pointer;
}
<div class="wrapper">
    <div class="tooltip">
    189k Likes
    </div>
        <div class="button">
        <img src="https://cdn2.iconfinder.com/data/icons/metro-uinvert-dock/256/Twitter_alt_3.png"/>
        </div>
</div>
    
<div class="wrapper">
    <div class="tooltip">
    200 Followers
    </div>
        <div class="button">
        <img src="http://lakemacholidayparks.com.au/wp-content/uploads/2014/09/facebook-icon.png"/>
        </div>

You can view the code in action on jsfiddle.net: https://jsfiddle.net/3y8pcv69/

Answer №1

Instead of selecting all elements with the class .tooltip, you can just target the previous element from your button, which is the tooltip itself. Here's a more efficient way to achieve this:

$(function() {
    $('.button').hover(function() { 
        $(this).prev('.tooltip').stop().fadeTo("fast", 0.8); 
    }, function() { 
        $(this).prev('.tooltip').fadeTo("fast", 0.0); 
    });
});

Check out the demo on JSFiddle

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 correctly adding a JSON output to a dropdown menu option

What is the correct way to add JSON results to a select option? Here is a sample of JSON data. AJAX code example: $.ajax({ url: 'sessions.php', type: 'post', datatype: 'json', data: { from: $ ...

Failed to transfer CryptoKey to Express server

When I generate a CryptoKeyPair object on the client using the WebCrypto API, and try to send it to my express server using the fetch API, the req.body on the server side ends up being an empty object. What could be causing this issue? This is how I am ge ...

Why isn't my CSS button changing color on hover?

div ul li a.button:hover { text-color:#FF0000; background: #0040FF; } I have been attempting to create buttons that change color and text when hovered over. Despite trying different methods, the changes do not seem to be taking effect. Below is the co ...

Preserving spacing using minimum widths

Looking for some help with a page layout issue. I have a header on my page with a title and menu. Currently, the header has a margin and a minimum width set to the width of the menu. However, when the user resizes the window and reaches the minimum width, ...

Varied content types required for unique elements within form data

I am having trouble including the content-type application/json with the initial element of my form data. This is the code I am using: var fd = new FormData(); fd.append('addBank', JSON.stringify(reqData.addBank[0])); fd.append('bankProof& ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this. The issue arises because the PDF path is generated dynamically at runti ...

Enhancing the Appearance of Multilevel Dropdown Menus

Creating a navigation bar with a multilevel dropdown on it is giving me trouble. I can easily style the text when hovering over my navbar, but styling the insides of the dropdown seems to be a challenge. I've attempted to style it myself without succe ...

Using reduce() to group items in an array based on a specific object property

Creating a new array grouped by the property 'desc' of the objects within an existing array is my current task. Here is how I envision it: const sourceArray = [ { id: 'id1', sourceDesc: 'foo', prop1: 'ignoreme', p ...

What is the best way to fill an array with specific dropdown values in Angular?

My task is to dynamically populate an array with all selected values from a mat-select dropdown in Angular. The end goal is to generate an input field for each selected value, similar to the example shown below: Image I've been contemplating calling ...

Arranging columns in a row with some breathing room using Bootstrap's grid system

On my webpage, I have multiple repetitive product listings displayed. <div class="col-lg-12 col-md-12 col-sm-12 "> <div class="row"> @foreach (var item in Model.Products) { ...

Update the div using AJAX following the form submission

I'm having trouble displaying the loading image before every AJAX response when I submit the form. Currently, the image only shows on the first submission. Here's the code I'm using: $('form.ajax').on('submit', function ...

Soundcloud's HTML5 Widget occasionally halts loading unexpectedly

Currently, I am building a website that features the Soundcloud HTML5 widget. However, I have encountered an issue where the widget does not load properly. Initially, everything was functioning well, but after numerous page refreshes during development, th ...

JavaScript Code for Executing Function on Checkbox Checked/Unchecked

My goal is to display an image when the checkbox is checked and show text when it is unchecked. However, I am facing an issue where the text does not appear when I uncheck the checkbox. <input type="checkbox" id="checkword" onchang ...

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

Having trouble with Ajax calls in Sencha Touch 2?

In my application, I have a simple function that is called from the launch() function: function makeAjaxCall(){ Ext.Ajax.request({ url: 'ajax/Hello!', // The request should be sent to host/ajax URL as an HTTP GET request / ...

The discovery of a commitment in the statement. The automation of unwrapping promises within Angular statements has been phased out

Struggling with errors while setting up a new AngularJS project. Here is the code for my app and controller; var app = angular.module('myApp', ['localytics.directives']) .config(['$parseProvider', function ($parseProvide ...

Creating a form that can identify both letters and numbers using JavaScript

Is it possible to create an <input> field that can recognize both letters and numbers while disregarding spaces and capitalization? Here is my current progress, aiming for the feedback to display as "right" when 9 H 6 U 8 f is entered in the field, ...

Is there a way to determine if a click occurred outside of a div without relying on stopPropagation and target event?

My goal is to track multiple div elements and determine if a click occurs outside of any of these divs. I am looking for a solution that does not involve using stopPropagation or event.target as they have negative effects. Is there an alternative method to ...

Divide the parsed rss findings into separate parts

I am in the process of developing a project that involves aggregating job listings from various websites by parsing their RSS feeds. I am utilizing rss-parser for this purpose. Each feed has its own format for the title field, resulting in varying structu ...