Jquery problems impacting every element rather than only one

I'm currently experimenting with a small project where I have multiple div elements containing an image, h1 tag, and p tag all sharing the same class name. My goal is to add CSS effects that make the h1 tag and p tag slide into view and become visible when hovering over the specific div element they are within.

The issue I'm facing is that the code I've implemented applies the effects to all div elements instead of just the one being hovered on.

Below is a glimpse of my code:

The CSS

<style>
    .col-md-4 {
        margin-top: 30px;
        margin-bottom: 26px;
        color: white;

    }

    .title-1 {
        margin-top: -260px;
        text-align: center;
        position: relative;
        top: -104px;
        opacity: 0;
        transition: top 1s, opacity 1s;
    }

    .paragraph-1 {
        margin-top: 160px;
        text-align: center;
        position: relative;
        top: 60px;
        opacity: 0;
        transition: top 1s, opacity 1s;
    }

    .title-2 {
        margin-top: -260px;
        text-align: center;
        position: relative;
        top: -20px;
        opacity: 1;
        transition: top 1s, opacity 1s;
    }

    .paragraph-2 {
        margin-top: 160px;
        text-align: center;
        position: relative;
        top: -20px;
        opacity: 1;
         transition: top 1s, opacity 1s;
    }

Here's the jQuery snippet

<script>
    $('document').ready(function() {
        $('.col-md-4').mouseover(function() {
            $('h1').addClass('title-2');
            $('h1').removeClass('title-1');
            $('p').addClass('paragraph-2');
            $('p').removeClass('paragraph-1');

        });

        $('.col-md-4').mouseleave(function() {
            $('h1').addClass('title-1');
            $('h1').removeClass('title-2');
            $('p').addClass('paragraph-1');
            $('p').removeClass('paragraph-2');
        });
    });
</script>

And this is how the HTML structure looks like

 <div class="col-md-4">
                <img src="images/remodeling3.jpg" class="img">
                <h1 class="title-1">Title Here</h1>
                <p class="paragraph-1">Paragraph here.</p>
            </div>

             <div class="col-md-4">
                 <img src="images/remodeling3.jpg" class="img">
                <h1 class="title-1">Title Here</h1>
                <p class="paragraph-1">Paragraph here.</p>
            </div>

             <!-- More similar divs -->

I understand the need to use the 'this' keyword to target the current item, but I'm struggling to implement it correctly in order to achieve the desired effects with my existing code. Any assistance would be greatly appreciated.

Answer №1

Your code needs to be modified as follows:

<script>
    $('document').ready(function() {
        $('.col-md-4').mouseover(function() {

        $(this).find('h1').addClass('title-2');
            $(this).find('h1').removeClass('title-1');
            $(this).find('p').addClass('paragraph-2');
           $(this).find('p').removeClass('paragraph-1');

        });

        $('.col-md-4').mouseleave(function() {
            $(this).find('h1').addClass('title-1');
            $(this).find('h1').removeClass('title-2');
            $(this).find('p').addClass('paragraph-1');
           $(this).find('p').removeClass('paragraph-2');
        });
    });



</script>

Answer №2

To specifically target the children within each col-md-4 element, you can utilize this along with find(), as shown below:

$( this ).find('element').addClass('class');

You have the opportunity to optimize your code by merging removeClass and addClass.

$('document').ready(function() {
    $('.col-md-4').mouseover(function() {
        $( this ).find('h1').removeClass('title-1').addClass('title-2');
        $( this ).find('p').removeClass('paragraph-1').addClass('paragraph-2');
    });

    $('.col-md-4').mouseleave(function() {
        $( this ).find('h1').removeClass('title-2').addClass('title-1');
        $( this ).find('p').removeClass('paragraph-2').addClass('paragraph-1');
    });
});

An alternative approach is to employ toggleClass, which enables one to remove and add classes simultaneously. It's worth noting that if the class being removed isn't initially present on the element, both classes will either be deactivated or activated.

$('document').ready(function() {
    $('.col-md-4').mouseover(function() {
        $( this ).find('h1').toggleClass('title-1 title-2');
        $( this ).find('p').toggleClass('paragraph-1 paragraph-2');
    });

    $('.col-md-4').mouseleave(function() {
        $( this ).find('h1').toggleClass('title-2 title-1');
        $( this ).find('p').toggleClass('paragraph-2 paragraph-1');
    });
});

Answer №3

You have the option to employ a script similar to this:

/**
 * Perform Method when DOM is ready
 * @return {[type]}   [description]
 */
$('document').ready(function() {
  // script for mouse over event
  $('.col-md-4').mouseover(function() {
    // storing $(this) object in a local variable as $this
    var $this = $(this);
    // locating <H1> tag within .col-md-4 current container where the event is occurring
    $this.find('h1')
      // initially adding desired class
      .addClass('title-2')
      // then removing class using jQuery Chaining Method WOAH!!
      .removeClass('title-1');
    // same approach for <P> tag as previously done for <H1>
    $this.find('p').addClass('paragraph-2').removeClass('paragraph-1');

  });

  // script for mouse leave event
  $('.col-md-4').mouseleave(function() {
    // storing $(this) object in a local variable as $this
    var $this = $(this);
    // locating <H1> tag within .col-md-4 current container where the event is occurring
    $this.find('h1')
      // initially adding desired class
      .addClass('title-1')
      // then removing class using jQuery Chaining Method WOAH!!
      .removeClass('title-2');
    // same approach for <P> tag as previously done for <H1>
    $this.find('p').addClass('paragraph-1').removeClass('paragraph-2');
  });
});

VIEW LIVE DEMO

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

Sending information to the styles feature in Angular 2

Is there a way to transfer data from an Angular tag to the styles in the @Component? Take a look at my component: import { Component, Input } from '@angular/core'; @Component({ selector: 'icon', template: `<svg class="icon"> ...

What is the best way to display lengthy content using a pair of HTML tags?

I am facing an issue with my Angular4 app where I have a <md-card-content> tag on part of my page. Inside this tag, I am trying to display some content within a <p> tag which has a maximum height of 20cm. While this setup works fine for short ...

JavaScript preloader function isn't functioning properly when paired with a button

I'm currently working on developing a preliminary landing page for my game using JavaScript. I have integrated a class that overlays my main content, and added an 'onclick' function named fadeOut() for my button in JavaScript. However, the f ...

Counting checkboxes in jQuery version 1.9

I recently upgraded my website from jQuery 1.6 to jQuery 1.9.1, and now some of my old code is not working as expected. Specifically, I have a piece of code that handles checkboxes in table rows, allowing only up to 5 checkboxes to be active at once and di ...

When removing the class "img-responsive" from an image, the bootstrap columns begin to overlap

Just starting out with Bootstrap while working on an Angular2 project and I have a question. Currently, I have a map-component taking up 3 columns on the left-hand side, but every time I resize the browser, the image also resizes. I want the image to rema ...

What causes the sub-menus to move even when they are set to position: absolute?

The sub-menu items under the about link appear to be slightly shifted from the left, despite setting it with position: absolute; left: 0px. I aim to have all menu items (including sub-menus) perfectly overlapped. Below is the code snippet: <html> & ...

What is the best way to select a specific descendant class deep within the DOM using jQuery?

I am facing a situation where I have multiple parent divs with numerous children. Within all the parents, there is a child element deep inside called .nxt. My goal is to only hide the .nxt divs within the parent1 div, without affecting the other two paren ...

Is it possible to verify the user's authentication by confirming the presence of a JWT in their localStorage?

I am currently working on a project that requires JWT authentication. I have set up a registration form and login page where users receive an authorityToken and it is saved in localStorage. Once the user logs into their account : ` $("#btnLogin").click( ...

Error message: "Invalid syntax detected while using the jQuery UI select plugin"

While utilizing jquery 1.8.1, I encountered a particular error message related to the jquery ui select plugin within the second code snippet. The specific error is shown below: Uncaught Error: Syntax error, unrecognized expression: li:not(.ui-selectmenu-g ...

What is the method for stretching the navbar and content to fill the entire viewport in Bootstrap?

Can anyone help me with an issue regarding a navigation bar and content created in Bootstrap 5? I'm trying to use vh-100 to make both the navigation bar and content stay on the view page without a scrollbar. However, the size of the navigation bar is ...

What is the complete pathway in CSS?

Consider this scenario: within my CSS file, there is a line of code used to display an image - specifically, a label icon located in the sidebar. background-image:url(../assets/images/icons/arrow_state_grey_expanded.png); However, due to its relative pat ...

Is async programming synonymous with multi-threading?

Discussing a JavaScript code that utilizes the setInterval function every 2 seconds. There is also an animation event for some control triggered by the onblur event. If the onblur event occurs (along with the animation), there is a possibility of encount ...

Deactivate a function when the dropdown input is selected

I'm currently using a function to attach scroll events to a slider element for navigating through slides. However, I want to temporarily disable this function in specific situations - such as when a dropdown is in focus - to allow smooth scrolling thr ...

Ways to access text content in an HtmlTableCellElement

I am currently working on a jQuery tic-tac-toe project and facing an issue with iterating through the board to save the values of each cell in an array. I have tried using .text() and .value(), but both returned undefined index.html: <html> < ...

Navigating Links Inside a jQuery Mobile Panel

I've been searching high and low for the solution to this issue, but so far, I haven't had any luck. My dilemma lies within my jQuery mobile panel as I attempt to navigate to a specific section of the page: <div data-role="page" id="home"> ...

A versatile HTML5 element that can be placed anywhere on the webpage

I am currently developing a library that assists in dynamically loading design. For example: A.EJS This is the a.ejs file B.EJS <b><%= phoxy.DeferRender('a', {}) %></b> Will be presented as <b><div id="phoxy_defe ...

Troubleshooting: Issues with jQuery's clone() function

I'm facing an issue with the code below. It works correctly when I use td instead of p. $(document).ready(function() { $("button").click(function() { $("th:contains('2G Band') ~ p").clone().appendTo("#2g"); }); }); <script src= ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

CakePHP includes built-in jQuery pagination and sorting functionality

Does CakePHP have built-in jQuery pagination and sorting functionality similar to regular jQuery? I have searched online but couldn't find relevant information. Can someone please point me in the right direction? Thank you, Himanshu Sharma ...