How to apply jQuery addClass to only the following target element and not all elements on the entire webpage

Currently, I am using jQuery to create an animation effect on a hidden element (which is an image description) so that it becomes visible when hovering over an image.

Although the code snippet I found does work, it has a downside - all the hidden image descriptions on the page become visible simultaneously. My goal is for only the relevant one to be visible.

I have been attempting to implement $(this) and next() in my code without fully grasping how they function.

var item = $('p.image-description');

$('.popup-image').hover(
    function () {
        item.addClass('is-visible');

        setTimeout(function () {
            item.addClass('is-open');
        }, 20);
    },
    function () {
        item.removeClass('is-open');

        item.one('transitionend', function (e) {
            item.removeClass('is-visible');
        });
    }
);
.masonry-entry .popup-image p.image-description {
  display: none;
  opacity: 0;
  transition: all 0.3s linear;
}

.masonry-entry .popup-image p.image-description.is-visible {
  display: block;
}

.masonry-entry .popup-image p.image-description.is-open {
  margin-left: 0px;
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="masonry-entry">
  <a class="popup-image" href="http://lorempixel.com/400/200/">
    <img src="http://lorempixel.com/400/200/" />
    <p class="image-description">Text here</p>
  </a>
</div>
<div class="masonry-entry">
  <a class="popup-image" href="http://lorempixel.com/400/200/">
    <img src="http://lorempixel.com/400/200/" />
    <p class="image-description">Text here</p>
  </a>
</div>
<div class="masonry-entry">
  <a class="popup-image" href="http://lorempixel.com/400/200/">
    <img src="http://lorempixel.com/400/200/" />
    <p class="image-description">Text here</p>
  </a>
</div>

My aim is to hover over ".popup-image" and only have the corresponding "p.image-description" appear, rather than all the "p.image-description"s on the page at once.

Answer №1

When you retrieve a group of elements with the class .image-description, you are using the following line of code:

var items = $('p.image-description');

Any actions performed on 'items', such as adding the class 'is-visible', will affect all elements in the collection. It is more accurate to consider what you have as a collection of items rather than just one item.

To target the specific element being hovered over and apply classes to its associated 'image-description', you should use $(this).

Here is an example:

$('.popup-image').hover(function () {
    var imageHovered = $(this); // providing clarity
    var description = imageHovered.find('.image-description'); // for explanation purposes only
    description.addClass('is-visible');

    setTimeout(function () {
        description.addClass('is-open');
    }, 20);
}, function () {
    var desc = $(this).find('.image-description'); 
    desc.removeClass('is-open');

    desc.one('transitionend', function () {
        desc.removeClass('is-visible');
    });
});

Answer №2

Utilize this to display the specific element and use find to locate the image-description

var item = '';
var timeOut = 0;
$('.popup-image').hover( 
        function (e){
       
        item =  $(this).find(' p.image-description');    
       
            item.addClass('is-visible');

             timeOut = setTimeout(function () {
    item.addClass('is-open');
}, 20);

},
        function() {
        item =  $(this).find(' p.image-description');    
            item.removeClass('is-open');

            item.one('transitionend', function(e) {
                item.removeClass('is-visible');
        });
        clearTimeout(timeOut);
}
    );
.masonry-entry .popup-image p.image-description{
    display: none;
    opacity: 0;
    transition: all .3s linear;
}
.masonry-entry .popup-image p.image-description.is-visible {
    display: block;
}
.masonry-entry .popup-image p.image-description.is-open {
    margin-left: 0px;
    opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="masonry-entry">
    <a class="popup-image" href="http://lorempixel.com/400/200/">
        <img src="http://lorempixel.com/400/200/" />
        <p class="image-description">Text here</p>
   </a>
</div>
<div class="masonry-entry">
    <a class="popup-image" href="http://lorempixel.com/400/200/">
        <img src="http://lorempixel.com/400/200/" />
        <p class="image-description">Text here</p>
   </a>
</div>
<div class="masonry-entry">
    <a class="popup-image" href="http://lorempixel.com/400/200/">
        <img src="http://lorempixel.com/400/200/">
        <p class="image-description">Text here</p>
   </a>
</div>

Answer №3

If you want to add a class to the first sibling element after '#my-element', you should use

$('#my-element').next().first().addClass('my-class');
.

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 method for ensuring the banner image is visible behind the transparent navigation bar?

I recently used Bootstrap 4 to write the code below. In the image provided, I have outlined what my goal is with this code. Thank you! https://i.sstatic.net/oB6b6.jpg <style> div.jumbotron { background: #458392 url("img/ban ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

PrimeFaces: Achieving Conditional Coloring Based on Status (Passed/Failed)

Attempting to dynamically change the color of a column based on its status value (Passed/Failed/InProgress) using jQuery. I tried copying and pasting the table into jsfiddle, where it worked. However, when implemented in the actual XHTML file, the jQuery ...

HTML combined with the Internet Explorer versions 6, 7, 8, and 9 can result in a div element that

My HTML code includes a <div>Some text</div>, and I am looking to ensure it is unclickable (allowing elements under the div to be selected instead), unselectable (preventing users from selecting text inside the div), while still being visible.. ...

jQuery can be used to deactivate the submit button

I am trying to prevent users from clicking the submit button multiple times on my form. I attempted to do this using jQuery as shown below: $('form').submit(function() { var formId = this.id; if (formId != ''){ $(&apo ...

Tips for inserting a new entry into the KendoUI DataSource module

I have set up a KendoUI DataSource on my webpage that retrieves data in JSON format from a method. Here is the script I am using: <script id="template" type="text/x-kendo-template"> <tr> <td>#= ID #</td> ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Achieve full div coverage within parent container

I am seeking assistance with positioning divs correctly within my HTML structure: <div class="container"> <div class="item"> <div class="left"> lorem lorem </div> <div class="right"> ...

Is the JavaScript progress bar dysfunctional when used with object-oriented JavaScript code, but functions properly with arrow functions?

After posting a question about the JavaScript progress bar not working with object-oriented JavaScript code on Stack Overflow, I decided to try rewriting the script using arrow functions. Here is the new code: document.getElementById("barButton").addEve ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Using AngularJS to load a custom JavaScript file within an ng-view

In my sample project, I have utilized Angular Js for the front-end. I have developed a template and implemented dynamic loading of views based on requirements. For this application, I am utilizing angular, jquery, and cusotm js. The structure of my templat ...

Retrieve the nearest identifier text from the tables

I have a table on my webpage with some data: <tbody id="carga"> <tr> <td>1</td> <td id="nombre">esteban</td> <td id="apellido">aguirre</td> <td>N/A</td> <td>N/A</td ...

What is the best way to manage events within datalist options using Vue.js?

I have a specific requirement where I need to implement a feature in my data list. When a user selects an option from the datalist, I must update other input fields based on that selection. Below is the code snippet for my input field and Datalist: <i ...

Using an HTML5 image icon as an input placeholder

Is there a way to incorporate an image icon into an input placeholder and have it disappear when the user starts typing, across all browsers? In trying to achieve this, I successfully implemented a solution for webkit (Safari+Chrome) using ::-webkit-input ...

Stop the creation of new div elements once the minimum height has been reached or when text is past

Here is the HTML code I am working with: <div id='parent' align='right' dir='rtl' style=padding:0px;margin:0px;font-weight:bold;width:300px;height:auto;min-height:300px; "'<div align='right' dir='rt ...

Is it possible to have two router.js files within a single Angular project?

Encountering a dilemma in my Angular UI routing project with rendering the view. Contemplating using two router.js files. Is it feasible to include two router.js files in one project? What drawbacks might arise from this approach? ...

Troubleshooting: jQuery AJAX not Invoking C# Method in ASP.NET MVC Application

I am attempting to initiate a call to the controller from the views using jQuery ajax, however, it seems like the controller is not being called. The goal is to pass the token value obtained on the registration page to the controller in order to utilize it ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

The surprising margins that Bootstrap sneaks into columns

It seems like bootstrap is mysteriously including an unseen margin in my column classes. Even after inspecting an element labeled as 'col-lg-3,' there is no visible margin CSS, and attempting to manually add margin:0 still results in a margin bei ...

Initiate a POST request using cURL to interact with an AJAX

Struggling with implementing the Zendesk API curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \ -H "Content-Type: ...