Having trouble with my jQuery .hover() code not running as expected

Whenever I hover over my divs, I want them to change color. However, the code doesn't seem to be working as expected when I try to do so. I suspect that the issue might be related to the z-index property used in the class that I am trying to hover over.

Below is the HTML with accompanying script:

$(".eventContents").hover(
  function() {
    $(".eventContents").css("background-color", "yellow");
  })


//making events square
    var cw = $('.eventContain').width();
    $('.eventContain').css({
        'height': cw + 'px'
    });
.eventContain {
  position: relative;
  margin-bottom: 10px;
  z-index: -1;
  background-size: cover;
}
.eventContents {
  color: white;
  padding: 5px;
  position: absolute;
  bottom: 0;
  left: 0;
}
.eventContents h2 {
  font-size: 2em;
  font-family: 'Montserrat', sans-serif;
}
.eventContents p {
  font-size: 1em;
  font-family: 'Roboto', sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="events">
  <row>
    <div class="col-sm-4">
      <div class="eventContain" style="background-image:url(img/events/leaf.jpg)">
        <div class="eventContents">
          <h2 class="eventName">Title of Event</h2>
          <p>short description goes about here.</p>
        </div>
      </div>
    </div>
    <div class="col-sm-4">
      <div class="eventContain" style="background-image:url(img/events/12.jpg)">
        <div class="eventContents">
          <h2 class="eventName">Title of Event</h2>
          <p>short description goes about here.</p>
        </div>
      </div>
    </div>
    <div class="col-sm-4">
      <div class="eventContain" style="background-image:url(img/events/1.jpg)">
        <div class="eventContents">
          <h2 class="eventName">Title of Event</h2>
          <p>short description goes about here.</p>
        </div>
      </div>
    </div>
  </row>

</section>

The problem is more noticeable in the following fiddle: https://jsfiddle.net/jakexia72/x7jLp17z/#&togetherjs=os0pjD0RNr

Answer №1

It appears to be functioning correctly for me, if I have understood it right. However, here is an alternative method to hover on and off using this instead of repeating .eventContents twice more.

$('.eventContents').hover(
  function() {
    $(this).css('background-color', 'yellow');
  }, 
  function() {
    $(this).css('background-color', 'red');
  }
);

fiddle

https://jsfiddle.net/Hastig/4fjn0ndb/1/

Answer №2

The elements are being properly hovered and the code is running as intended in my tests. The issue may be related to your elements having a position:absolute; and overlapping one another. Additionally, these elements lack a specified height, which is essential for div elements (not img). I recommend reviewing your code more thoroughly.

To ensure visibility of your .eventContents, consider adding top:0px; since it appears hidden on top in this example scenario.

Lastly, if you wish to target the specific hovered element, utilize $(this) instead of the class name. This will ensure that the code executes only for the currently hovered element, rather than all elements with the same class.

Answer №3

The issue with the hover functionality not working is due to the negative z-index. To resolve this, ensure that the element intended for hovering has a positive z-index. In order to prevent interference with the top navigation bar, relocate the nav bar to the end of the HTML code file so it naturally displays on top without requiring a negative z-index adjustment for eventContain.

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

Chrome compatibility issue with margin collapsing

I'm currently working on a website and encountering a CSS issue. It appears fine in Firefox, but has some odd layout problems in Chrome. I would appreciate any assistance on how to resolve this issue. On the main page, if you scroll down, you'll ...

Importing a module directly from the umd distribution may yield a distinct outcome compared to importing it

Within my Vite/Vue3 application, I am importing two identical umd.js files: One is located at node_modules/foo/bar/dist/foobar.umd.js (imported with alias @foo = node_modules/@foo). The second .umd.js file can be found at <root dir>/foo/bar/dist/ ...

Turning a string array into a basic array can be achieved through a few simple steps

While I am aware that this question has been posed multiple times, my scenario is slightly unique. Despite exhausting numerous methods, I have yet to discover a suitable workaround. $array = ["9","8","7","6","5"]; //result of javascript JSON.stringify() ...

My code is experiencing issues with JQuery's $.post, $.get, and $.ajax functions not functioning properly

Struggling to post and retrieve data from a php file using JQuery? Feel like you've tried everything from post to get and $.ajax method but still no luck? The php code doesn't seem to be getting called? Take a look at myUpload.php file which suc ...

How can you fix a navbar that won't stay in place?

I'm facing an issue with this example: When I scroll, the navbar moves along due to the fixed property, which affects the overall look. How can I make it disappear when scrolling, while keeping the logo intact? Can someone suggest if this layout is ...

Dealing with the percentage sign in table names during data retrieval

When using React and Express to retrieve and store data in JSON format, what is the correct way to reference tables that have a percentage sign in their name? componentDidMount() { // Retrieve data from http://localhost:5000/citystats, sort by ID, t ...

Using identical CSS styles across various classes in material UI

Three classes have been defined with identical CSS properties. const useStyles = makeStyles((theme) => ({ classA: { color: 'green' }, classB: { color: 'green' }, classC: { color: 'green' } }) Is there a way to combin ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Create a user-friendly responsive tooltip in Javascript/jQuery with a convenient close

Looking to implement a tooltip feature that appears when a text box is focused on my responsive website, and disappears when it loses focus. Can anyone recommend the best JavaScript/jQuery library for this specific purpose? Here are my requirements: T ...

How can you create a blurred effect on a navbar?

Looking to achieve a unique blur effect in the background of my navbar component. The standard CSS blur effect isn't giving me the desired result, so I'm seeking some guidance on how to customize it. For example: https://i.sstatic.net/bPEXZ.png ...

Connecting to a fresh dynamic route does not impact the getInitialProps data

I am struggling to understand the difference between componentDidMount and getInitialProps. Despite my best efforts to research, I still can't figure out when to use each one in my specific case. Let me give you some context. I have a page called /co ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

Tips for employing clamp CSS to modify font size while maintaining alignment within a paper-inspired CSS grid

Currently, I am working on creating a responsive text section with a grid-like horizontal line resembling paper, and the challenge lies in aligning the text properly within this grid. While I can achieve this when the font size remains constant, I am curi ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

output a string from the write_html function in plotly

I am currently attempting to utilize plotly express to generate a string representation of a div object in HTML for integration with other packages. Although I have been following the documentation (Plotly v5.17.0), it seems that my attempts have not been ...

CSS Animations are effective in CodePen, but unfortunately, they do not function properly once integrated into an ASP.Net project

I created a unique design on codepen with a background animation, which functions properly there. However, when I integrate it into my ASP.Net Core project, the animation doesn't work as expected. The file references seem correct because the backgroun ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

Ways to modify textbox background shading when an error arises

I have a text box where I input an email address. If the email is in the wrong format, I want the background color of the text box to change. This is the jQuery code I have written: $(function() { $(':text').hover(function () { this ...