Choosing the *exact* element with jQuery

As a newcomer to jQuery, I'm attempting to apply a specific class to an individual image when hovering over a button. However, my initial approach did not yield the desired result.

The issue is that there are multiple .service sections, each containing its own .service button. Consequently, when I hover over a button, all the .service-image elements are affected simultaneously. I had hoped to rectify this by utilizing $(this) or find(), but I am struggling to find the right solution...

$(".service button").hover(function() {
  $(".service-image").toggleClass("raise");
});
.raise {
    transform: translateY(-10px);
    transition: all 0.2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="service home-service1">
  <div class="service-image">
    <img src="images/phone.png" alt="" />
  </div>
  <div class="service-title">
    <h2>Kiosk Renovation</h2>
  </div>
  <div class="service-text">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut feugiat quam sit amet vehicula auctor. Aliquam vel orci hendrerit, vestibulum ligula laoreet, faucibus mi.</p>
  </div>
  <button class="outline-on-dark">Explore</button>
</div>

Answer №1

Given that the <button> element is a sibling of the .service-image you are attempting to select (meaning they both have the same parent element with the class .service), the most effective approach would be to utilize the siblings() method. By specifying the .service-image selector within the siblings() function, you ensure that only the .service-image element within the .service container is targeted.

$('.service button').hover(function() {
  $(this).siblings('.service-image').toggleClass('raise');
});
.raise {
    transform: translateY(-10px);
    transition: all 0.2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="service home-service1">
  <div class="service-image">
    <img src="images/phone.png" alt="" />
  </div>
  <div class="service-title">
    <h2>Kiosk Renovation</h2>
  </div>
  <div class="service-text">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut feugiat quam sit amet vehicula auctor. Aliquam vel orci hendrerit, vestibulum ligula laoreet, faucibus mi.</p>
  </div>
  <button class="outline-on-dark">Explore</button>
</div>

Answer №2

Experiment with this:

$('service button').on('hover', function(event){
  $(this).siblings('.service-image').toggleClass('raise');
});

Your initial instinct was on point, since the button and certain image are part of the same parent element.

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

Stylish navigation menu with a subtle scrolling effect in the

Both the left panel and main content should have individual scrolling abilities. You can view a demonstration of this functionality here: http://plnkr.co/edit/Le6hPWwMm0pu5Ukm2cYg?p=preview Below is the CSS code required for this feature: html { ove ...

Ensure the page is always updated by automatically refreshing it with JavaScript each time it

I'm currently working on a web application that makes use of JQuery. Within my javascript code, there's a function triggered by an onclick event in the HTML which executes this line: $('#secondPage').load('pages/calendar.html&apos ...

Strategies for effective communication between client and server for websites containing a large volume of images

I am embarking on the creation of a comic book reading website that will host thousands of images stored on the server. Each series consists of hundreds of chapters, each containing numerous images. My goal is to efficiently display these images on my site ...

Toggle switch unable to reset upon reloading the page

Issue with Toggle Switch Not Resetting on Page Reload I am encountering a problem with a toggle switch I implemented from the W3schools example (link here). Unlike in the W3schools editor where it resets its state upon reload, my toggle switch remains in ...

What could be causing my nested child component to fail to display the content?

My current setup includes: Vue 2.5.16 Veux Vue router I have created a simple router view that searches for a child component within a parent component using the URL structure: /folders/parent-uuid/child-uuid Below is the code for the parent component ...

What steps should be taken to trigger an API call once 3 characters have been entered into a field

In my current project, I am dealing with a parent and child component setup. The child component includes an input field that will emit the user-entered value to the parent component using the following syntax: <parent-component (sendInputValue)="g ...

Efficient method for triggering a PHP exception using jQuery, AJAX, and JSON

Is it possible to efficiently handle PHP exceptions when making a JSON response through a jQuery/AJAX call? ...

Display tooltips on top of z-index stacking contexts

I am struggling to display a tooltip within a table field, on top of other fields and tables. The issue lies in the fact that the other tables and elements are housed within different DIVs that have set the CSS z-index property to 0. Even if I assign a hi ...

Tips for Limiting Upload Image Size with Maximum Width and Height

Is it possible to set a maximum width and height for an image before uploading it? I want the user to select a file, see a preview of the image, crop it, and then upload it to be saved in a directory. How can I enforce a max width and height limit before a ...

Issues with Array.push causing improper pushes

UPDATE: I have now included the res.send(json) that was missing from the snippet. I'm currently working on a project that involves extracting/scraping data from a website and consolidating it into JSON format. However, when I call the endpoint, the r ...

Struggling with finding the appropriate CSS selector?

I'm struggling to find the correct selector. Let me do my best to explain the situation: I am currently working on a project where I am unable to make changes to the HTML and JavaScript due to dynamic content and other constraints. Within this proj ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

Retrieving information from subscription

I am currently diving into Angular 2 and have successfully fetched data from my service. However, before displaying it on the view, I need to iterate over it using a for() loop. To achieve this, I have stored the fetched JSON data into an array. But I&apos ...

Creating an optimized dashboard in Next.js: Expert tips for securing pages with specific roles, seamlessly implementing JWT authentication without any distracting "flickering" effect

Given our current setup: We have a backend ready to use with JWT authentication and a custom Role-Based Access Control system There are 4 private pages specifically for unauthenticated users (login, signup, forgot password, reset password) Around 25 priva ...

Tips for expanding text within a grid

While working on an auto-fill grid that moves elements to the next line when the width reaches 800px, I encountered an issue with my text inside the grid not stretching. https://i.sstatic.net/OeJ3I.png Below is my CSS code: ul { display: grid; ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

The controller method in MVC is not receiving the expected data

Recently delving into MVC, I find myself faced with a challenge: editing a row and sending the modified data to a controller method using jQuery and AJAX. Upon clicking the edit button, the designated row transforms into textboxes and reveals a "save" `Act ...

Error encountered when attempting to upload a file using Angular and Firebase: "[object Object]"

UPDATE : After some investigation, I finally discovered the solution which required specifying the file name in the reference : this.fireStorage.storage.ref(file.name).put(file); I have been attempting to upload a file to FireStorage, but I am encounteri ...

What is the best way to dynamically include CSS in AngularJS?

Hello, I am currently attempting to add CSS dynamically but for some reason it is not working. Below you will find the code that I have been using: angular.module('myApp', [ 'myApp.controllers','myApp.services']). config([&ap ...

Updating values using events within a v-for loop in a Vue template: A step-by-step guide

Just starting out with Vue and Laravel! Currently, I am retrieving data from an API Resource in Laravel. The API consists of 2 fields: Goal Value Here is the code snippet: <template> <div class="container"> <h1> Progress ...