Implementing the switchClass function on a parent class when hovering over a child class, while ensuring that only the specific divs are targeted and not others with the

Currently using the .switchClass function on both the .container divs whenever I hover, causing all child1 elements within these containers to change from 100% width to 40% width. However, I only want this switch to occur on the specific container that I'm hovering over. Avoiding the use of IDs due to the large number of rows I need to create, approximately 30 in total.

The layout consists of multiple rows with a container followed by two side-by-side divs known as child1 and child2. During the default state, child1 spans the full width of the container, but upon hovering over said container, I aim to have both child1 and child2 slide over, resulting in child1 being 40% wide and child2 adjusting its width automatically. The current implementation utilizes the switchClass function to achieve this transition effectively.

Despite having successfully implemented the animation, the issue arises when hovering over one container triggers the effect on all divs bearing the "container" class. My understanding of jQuery is self-taught through online resources like Google and StackOverflow, so my knowledge is rather limited, and I've yet to explore many other functions.

Suggestions advising the use of $(this) as the selector have been found but incorporating it while switching the class of child1 based on container hover remains challenging. It ends up attempting to alter the class of .container itself instead of isolating it for each hover event.

Resorting to unique IDs has been avoided due to the high quantity of rows required on the page. Aiming to provide brief summaries related to each image upon hover without compromising performance or code cleanliness.

Reference jsfiddle: https://jsfiddle.net/sling/d6x4sfLn/

$(function() {
  $(".container").on('click', function() {
    $(".image-card").switchClass("image-card", "image-card-hover", 1000);
    $(".image-card-hover").switchClass("image-card-hover", "image-card", 1000);

  });
});
.container {
  width: 100%;
  height: 50vh;
  display: block;
  overflow: hidden;
  .image-h2 {
    color: white;
    padding: 1px;
    margin: 0;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
  }
  .image-card {
    background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
    background-size: cover;
    background-position: center;
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block;
  }
  .image-card-hover {
    background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
    background-image: url("http://www.steves-digicams.com/blog/wp-content/uploads/2017/10/Nikon_D850_Sample_13.jpg");
    background-size: cover;
    background-position: center;
    width: 40%;
    height: 100%;
    position: relative;
    display: inline-block;
  }
  .text-card {
    display: inline-block;
    width: 40%;
    padding-left: 1em;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/assets/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container" id="first">
  <div class="image-card">
    <h2 class="image-h2">
      This is the first project
    </h2>
  </div>
  <div class="text-card">
    <h2>
      Title
    </h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin posuere urna non magna imperdiet, non commodo magna finibus. Integer vel lacus sit amet augue imperdiet malesuada. Praesent hendrerit gravida ligula, ac tempor sapien pharetra eget. Maecenas
      hendrerit, odio quis eleifend vehicula, lacus dui pretium urna, quis facilisis tortor augue eget ipsum. Sed viverra massa vitae pretium tristique. Quisque nec felis mi.
    </p>
  </div>
</div>

<div class="container" id="second">

  <div class="image-card">
    <h2 class="image-h2">
      This is the first project
    </h2>
  </div>
  <div class="text-card">
    <h2>
      Title
    </h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin posuere urna non magna imperdiet, non commodo magna finibus. Integer vel lacus sit amet augue imperdiet malesuada. Praesent hendrerit gravida ligula, ac tempor sapien pharetra eget. Maecenas
      hendrerit, odio quis eleifend vehicula, lacus dui pretium urna, quis facilisis tortor augue eget ipsum. Sed viverra massa vitae pretium tristique. Quisque nec felis mi.
    </p>
  </div>
</div>

All containers are currently activating the hover effect instead of just the targeted one.

Answer №1

To target elements within the same container, utilize the $(this) selector:

$(document).ready(function() {
  $(".container").on('click', function() {
    $(this).find(".image-card").toggleClass("image-card image-card-hover", 1000);
    $(this).find(".image-card-hover").toggleClass("image-card-hover image-card", 1000);

  });
});

Check out the code in action here!

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 best way to ensure that all elements on an HTML webpage stay centered regardless of zoom level?

My HTML and CSS skills are not at an expert level. Despite my best efforts, when I zoom in on the webpage I created, certain elements like the logo and language switcher appear broken. I'm unsure how to address this issue. Can someone please provide m ...

How can I determine if a user has reached the end of a non-scrollable div by utilizing HostListener and directives within Angular?

In my Angular project, I have designed a main layout using flex display with specific height and overflow settings. The main content div inside this layout has its own unique styling to ensure consistent appearance for any components inserted within it. By ...

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

I am experiencing issues with a few of my design choices not functioning correctly

I am facing issues with some of my styles. I have put in a lot of effort, but there seems to be a problem with my menu. The last part of my CSS is not functioning correctly. When hovering over the menu content, I want it to turn black and... #site_menu { ...

Looking to find the video code in the page source and figure out how to get the video to play

I have a requirement where I must embed the video code directly in a blog post. After figuring out the necessary code for the video and saving it in a html file named video.html, I encountered an issue when trying to upload the file to the blog. Only the ...

What is the best way to eliminate the outer gutter in a 3-column grid using Bootstrap 3?

Check out this fiddle for more information. http://jsfiddle.net/Nb5C7/ I am curious about the blue gutter on the ends, which seems to be caused by auto margin. How can I get rid of it? In another example provided here , I was able to remove the gutter u ...

How do I efficiently render multiple form field components in React CSS when two of them have different flex directions?

I need to find a way to dynamically iterate through multiple input components. All inputs follow the same style pattern except for 'first name' and 'last name', which should be aligned in one row with different widths. <div style={{f ...

Creating a loop to iterate through JSON data being received

I successfully used JSON to display data, but I am now wondering how I can print all the database entries into a div or table. JavaScript $(document).ready(function() { $.ajax({ type : 'POST', url : 'server.php', dataTyp ...

The process of combining a CssStyleCollection with a System.Web.UI.WebControls.Style

I am working with a list item and trying to apply styles using System.Web.UI.WebControls.Style. However, I noticed that there isn't a MergeStyle option similar to what's available for controls. Instead, there is an Attributes.CssStyle property of ...

Using JSON as a parameter in a Grails controller

Struggling with passing a Json array to a Grails controller and then to a Java class? Can't quite figure out how to correctly pass the params to the Java class? Here's the code snippet you need to focus on. AJAX POST: $('#matrixForm&apos ...

Maintain the basic structure while ensuring divs are properly aligned

Behold, my div structure! ONE // at the top level TWO THREE // two divs side by side in the middle level FOUR // residing at the bottom <div id="ONE"> <div></div> <div><img src="logo.png"></div> </div> < ...

The JavaScript file is not compatible with Internet Explorer 9

My website's JavaScript functions normally work on all browsers except for Internet Explorer 9. In IE7 and IE8, they also work normally. After extensive testing, I have concluded that the JS file simply does not work in IE9, but why is that? The curio ...

How can I display a JSON list of results in an IEnumerable type in a ViewBag using MVC?

My goal is to retrieve a list result in the type of IENumerable within the existing ViewBag that already contains a list. In the controller's action method, I am returning the list using ViewBag- [HttpGet] public ActionResult RangerCard() { var ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

How can the value of a button be displayed in an input box using an onclick function?

When the button '1' is clicked, it displays the value "1" inside a <!p> tag. However, the second button '2' does not display the value "2" in the input box. Even though both functions are identical. //Function with working func ...

Customize the color when clicking on a mat-slide-toggle

Whenever I click on the element, a shadow appears in the color that corresponds to the element, which is currently yellow https://i.sstatic.net/21BR4.png I would like to change that shadow to be green instead, but I am unsure of how to do so. Here is my ...

I'm having trouble displaying the Facebook page plugin on my HTML website

I encountered a minor issue. I attempted to add the "Facebook page plugin" on a test website. I copied the code from the official Facebook plugin page: <!-- 1. Include the JavaScript SDK on your page once, ideally right after the opening <body> t ...

Is it possible to hide and reveal specific form elements based on the selection of a checkbox?

Having issues with the code provided below, it's not working as expected. Can you help me figure out what I might be missing? HTML: <input id="id_code_col" type="checkbox" name="code_col"></input> SCRIPT: $(document).ready(function(){ ...

The day text function failed to return a value and instead gave back

I am having trouble figuring out where the mistake is in my function below. My goal is to retrieve the day value in string format. function getDayText(date){ var weekday = new Array(7); weekday[0]= "Sunday"; weekday[1] = "Monda ...