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

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Tips on concealing the visibility of a table row using PHP

My HTML table structure is quite simple: <style> .demo { width:100%; border:1px solid #C0C0C0; border-collapse:collapse; padding:5px; } .demo th { border:1px sol ...

What is the best way to vertically align a pseudo element image using CSS?

After looking for similar questions, none of the answers seem to be working for my specific issue. This is what I'm struggling with: I am attempting to insert and center a decorative bracket image before and after certain content in the following man ...

Tips for attaching event listeners to custom elements

Let's suppose I create a Vue component called Checkbox.vue that contains the following code. <template> <div class="checkbox"> <input id="checkbox" type="checkbox"> <label for="checkbox">Label</label> ...

The URL's ajax GET request is timing out despite it working fine in browsers and CURL

I came across a question similar to mine, but unfortunately it does not have an accepted answer. My issue lies with the ajax request timing out. Strangely enough, when I make a `GET` request using the browser or `curl` on the same URL, everything works pe ...

SASS: Issues with the @media query functionality

My SASS file is giving me trouble with the media query. The background color changes properly, but the text remains unaffected. I would greatly appreciate your assistance with this issue. Below is the HTML and SASS code snippets in question: <!-- HTM ...

Tips on automating clicking the cookie button using Selenium?

Currently, I am attempting to extract data from the following website. I need to access various subpages, but some of them are hidden behind a "load more" button. I decided to use Selenium to click the button, but I am encountering difficulty with getting ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

The Full Screen Button on Google Maps isn't functioning properly in a third-party mapping application

Below you will see the '+' icon which is also supposed to function as the full screen button. https://i.stack.imgur.com/IMvHa.png However, when clicked on, it does not expand to full screen as intended. I have attempted using some basic jQuery ...

When making an ajax request in Codeigniter, the form validation may return false

Greetings, I am in the process of creating a website using CI on Backend and I'm facing an issue with implementing a registration system without refreshing the page. When I use a post form submit, everything works fine with no errors. However, when at ...

Discovering with jQuery

Can we actually change the background color of '.preview-inner' to yellow from "#change_color"? <div id = "form-container> <input class="color-picker" id="change_color" type="text"> <div class="replacer"> <div class= ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...

Generate two separate CSS files (Mobile and Desktop versions) by compiling a Stylus (.styl) file using Node.js

Can a single Stylus file be compiled into two separate CSS files? For example, one optimized for mobile without the -moz and webkit elements, and another for cross-browser applications? Thank you. ...

Which element to use for creating a color palette - <img>, <div>, or <canvas>?

I am currently in the process of developing a color-picker component using HTML, CSS, and Javascript. One key question that I have is how to best implement a color palette similar to the one below: Putting aside browser compatibility concerns with IE8 or ...

The Ajax PHP function only works on the initial call

The function below calls a PHP file that returns results in JSON format, which are assigned to JavaScript values. The PHP function has been thoroughly tested and works as expected. The results are stored in variables until the market variable is changed wi ...

The .each() function is invoked just one time

Here is the code snippet I am working with: function validateFormInputs() { isValid = true; var counter = 0; $('.form-input input[type="text"]').each(function() { isValid = isValid && validateInput( $(this) ); counter ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...