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

The feature of jQuery validation that enables the use of numbers in the "data-val-date" attribute for MVC

I have implemented client side validation using jquery.validate.js and jquery.unobtrusive.ajax.js, both of which are referenced on my webpage. The form inputs are generated using @Html.TextBoxFor(). All client side validation is working correctly except f ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

Checking for mouse button press during Firefox mouse movement

Trying to drag a div without needing to add a mouseup function to avoid potential bugs if the user's mouse is outside the window. Tested with chrome, IE and firefox - "e.which" works fine in IE and chrome but firefox retains the last clicked button s ...

The process of transforming four columns into two columns and two rows

I am aiming to create a layout that displays 4 columns on desktop and then breaks down into 2 columns and 2 rows on smaller screens. https://i.stack.imgur.com/GZ4nQ.png https://i.stack.imgur.com/5ZCrQ.png Any suggestions on how I can achieve this layout ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Utilizing jQuery variables to manage various events simultaneously

Is it possible to set a variable that can be accessed and utilized in various events like mouseout, mouseenter, click, etc.? The code snippet looks something like this: $('a div') // Get the width and height of the image //var $img_ ...

Determine the specific value of an HTML table cell by specifying the column name for a specific row

One challenge I am facing is dynamically creating a table using JSON without knowing in advance the number of columns and/or rows that will be generated. I have successfully added a clicked event for the row that gets selected. In every table, there will ...

tips for expanding the size of your images

Hey there, I'm looking for some help with the code below. I need to increase the width of the images and remove the border of the slider div which is currently showing a white border that I want to get rid of. I am using JavaScript to display the imag ...

The Masonry Grid is leaving empty spaces unfilled

I've been experimenting with Sveltekit and SCSS to create a Masonry grid. However, I'm facing an issue where the items in my grid are not filling in the empty space as expected. Instead, they seem to be following the size of the largest image, le ...

The CSS styles are not being completely applied to the PHP function

My current task involves dealing with multiple folders containing images. When a link is clicked on the previous page, a unique $_GET variable is sent and processed by an if statement, triggering a function to search for and display all pictures within the ...

When you click on the submit button, it triggers the associated event

I have multiple text input fields where pressing the enter key should move focus to the next field. After reaching the last text input, I want the focus to be on the submit button without triggering its click event until the user presses enter again. The c ...

the combination of class and type functions as a jquery selector

<button class="actionButton default" type="submit"> Save</button> Can you select this button by both its class and type using a jQuery selector? I attempted the following, but it did not work: var saveBttn = $('.actionButton.default [ty ...

What is the proper way to provide login information for a webservice through a jquery ajax request?

I've been attempting to make an AJAX call using jQuery like this: $.ajax({ url: WEBSERVICE_URL, type: "GET", dataType: "application/json; charset=utf-8", username: "admin", // Most SAP ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

Error message: Laravel Ajax function encountered an undefined variable

I am facing an issue with my ajax submission to the database. When I click the submit button, I get an "undefined" value in the return response. The problem seems to be in the controller, specifically with the 'fname' variable. I'm unsure ab ...

How can you leverage jQuery to append a new parameter to the existing URL without causing a page refresh?

One of our clients is facing a challenge with their staff page on the website. When a visitor clicks on a staff member's name, jQuery is used to fade out the current bio and fade in the selected bio on the right side. Although this functionality work ...

Tailwind CSS - when it comes to styling, larger screen media queries are taking precedence over smaller media queries

Currently tackling screen responsiveness issues in a Nextjs + Tailwind CSS project. All Tailwind breakpoints are functioning correctly except for "sm" and below. Snippet of the problematic code: <div className="bg-red-200 sm:bg-white md:bg-gray-70 ...

XSLT - Dividing table into three columns while maintaining continuity on the same page

I'm looking for a solution where I can display a long two column table in a three-column page layout. The table should seamlessly flow from one column to the next, maintaining its headers throughout. Current attempts show the entire table in just one ...

Unable to send JSON object using the Jquery.post() method

I have a specific object that is created within my javascript application. poll_data[active_question] = { 'question': $('div.question_wrap textarea').attr('value'), 'answers': [ $(&a ...

When using Jquery, input can be appended on the last child element when a key

I am new to JavaScript and want to enhance my page's functionality using jQuery. Here is my current HTML: <div class="input_fields_wrap"> <div><ul class="inputList"></ul></div> </div> My goal ...