How to trigger a hover effect on a div and its child simultaneously using HTML and jQuery

Here's my concept:

I want the text to be contained within div elements with an integrated image, rather than just having fading in and out pictures. Here's my attempt:

#first{
    position: absolute;
}
#second{
    position: absolute;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
    position: absolute;
}
.text-box {
    position: absolute;
    height: 100%;
    text-align: center;
    width: 100%;
}
.text-box:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
 <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>

    </head>
    <h1 id="third">Contact</h1>
    <!-- <div class="image">-->

    <div id="first" onmouseenter="showSecondImage()" onmouseleave="hideSecondImage()">
        <h4 class="text-box ">Why?</h4>
        <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg" >
    </div>

    <div id="second">
        <h4 class="text-box">Why isn't it working?</h4>
        <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg" >
    </div>
    <script>
        $(".unbinded").unbind();
        function showSecondImage() {
            document.getElementById('second').style.opacity = 1;
        }
        function hideSecondImage() {
            document.getElementById('second').style.opacity = 0;
        }
    </script>

Why is it not functioning correctly? I thought I needed to unbind the onmouseenter and onmouseleave event listeners and bind the picture to respond when the mouse enters.. Any help would be appreciated as I am new to this.

Answer №1

To achieve this effect using CSS only, you can start by hiding the #second element and then make it appear when hovering over either #first or #second.

#first {
  position: absolute;
}

#second {
  position: absolute;
  -webkit-transition: all 500ms ease-in-out;
  -moz-transition: all 500ms ease-in-out;
  -ms-transition: all 500ms ease-in-out;
  -o-transition: all 500ms ease-in-out;
  transition: all 500ms ease-in-out;
  opacity: 0;
}

.text-box {
  position: absolute;
  height: 100%;
  text-align: center;
  width: 100%;
}

.text-box:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

#first:hover + #second, #second:hover {
  opacity: 1;
}
<h1 id="third">Contact</h1>

<div id="first">
  <h4 class="text-box">Why doesn't it work?</h4>
  <img class="img-responsive" src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/H-P/photoark-lion.png.adapt.945.1.jpg">
</div>

<div id="second">
  <h4 class="text-box">Why isn't it working?</h4>
  <img class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2015/06/09/16/03BB5E5A0000044D-3117010-image-a-25_1433862086692.jpg">
</div>

Answer №2

In the words of Coker, utilizing only CSS and the pseudo-selector :hover, you can achieve this effect.

            div
            {
                width:500px;
                height: 200px;
                cursor: pointer;
                background-size: cover;
                transition: background-image .6s ease-in-out;
            }
            .first
            {
                background-image: url("http://apopka.uhcpqdoe6fq4wtztv.netdna-cdn.com/wp-content/uploads/2016/03/spring-daffodils_2845661b.jpg");
            }
            .second
            {
                background-image: url("http://www.twitrcovers.com/wp-content/uploads/2012/11/Winter-snow-l.jpg");
            }
            .first:hover
            {
                background-image: url("http://trucosparadecorar.com/wp-content/uploads/2016/09/oto%C3%B1o2.jpg");
            }
            .second:hover
            {
                background-image: url("http://cadenaser00.epimg.net/ser/imagenes/2016/06/20/sociedad/1466419875_801497_1466420115_noticia_normal.jpg");
            }
            div p
            {
                color: white;
                text-align: center;
                font-size: 24px;
                position: relative;
                text-shadow: 1px 1px 10px black;
                top: 43%;
            }
            div:hover .hidden
            {
                display:block;
            }
            .hidden
            {
                display:none;
                font-size: 14px;
            }
            .shadow:hover
            {
                background: rgba(0,0,0,0.3);
            }
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Hola</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <div class="first">
            <div class="shadow">
                <p>Spring of Field</p>
                <p class="hidden">Spring is wonderful, unless for allergic people that die each year by.</p>
            </div>
        </div>
        <div class="second">
            <div class="shadow">
                <p>Snow world</p>
                <p class="hidden">Go in winter, after the snow doesn't exist anymore.</p>
            </div>
        </div>
    </body>
</html>

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

triggering controller on click event in JSP

Using a spring web application, I need to call a controller in a java file from a JSP file using an ajax function. How can I achieve this? <p class="bottom-slide-corners"> <a class="billing" href="#Billing"><spri ...

Is it possible to replace a server-side templating engine with Angular 2's server-side pre-rendering?

As a novice in web development, I have recently been exploring angular 1.x, react.js, and angular 2 (eventually deciding on angular 2). Lately, I've been intrigued by the concept of server-side pre-rendering. In my understanding, this process is ...

Challenges with rendering items in a FlatList component in React Native

I'm currently working on transferring data from a data.json file to video.js <Image source={{ uri: video.snippet.thumbnails.medium.url }} style={{ height: 200 }} /> and I want this file to be rendered in a flatlist <FlatList showsHorizo ...

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response. However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform t ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

The use of ExpressJs res.sendFile is not effective following the implementation of middleware

Currently, my focus is on mastering JWT and its implementation in Node.js with Express. I've developed a middleware that aims to authenticate users using a token: app.use(function(req, res, next) { if(req.headers.cookie) { var authentication = req.h ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

The magic of $.ajax lies in its ability to load an unexpected URL, diverging from my original

Every time I send a request using an absolute URL, Ajax is posting the wrong URL. For instance, when I request "http://localhost/app/home/session", it mistakenly calls "http://localhost/app/home/home/session" var baseURL = function(link) { var url = & ...

What is the best way to position the div element to the right side of the webpage?

Looking at my HTML code below, I am trying to reposition the 'site-logo' and 'nav-search-wrapper' div elements to the left side of the parent div (top-nav) and have the 'list' div element appear on the right side. However, the ...

How to retrieve data from a jQuery AJAX POST request?

I am working on a profile page that displays multiple images. I am trying to implement jQuery functionality to enable users to delete an image from the server without refreshing the entire page. The goal is to update the page dynamically by removing the di ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

Seeking to develop a unique domain-specific language tailored for generating HTML code

I have a vision to develop my own personalized domain-specific language that generates HTML. Essentially, I aim to design quizzes using my custom markup language and later have it transformed into HTML format. For instance: > What is your favorite col ...

How can I make a DIV occupy the entire vertical space of the page?

I am working on a Google Maps application that takes up the majority of the screen. However, I need to reserve a strip at the top for a menu bar. How can I ensure that the map div fills the remaining vertical space without being pushed past the bottom of ...

The outcome when submitting an HTML survey

I have a curiosity about what really happens when you click the submit button on an HTML survey like the one displayed below: <INPUT TYPE="radio" NAME="bev" VALUE="no" CHECKED>No beverage<BR> <INPUT TYPE="radio" NAME="bev" VALUE="tea">Te ...

What is the best method for assigning a default value to the file input tag in HTML?

Can anyone help me with this code snippet? <input name="GG" type="file" value="< ?php echo $data['image'] ?>"> I was trying to set a default value in the form edit, but it seems to not be working. Does anyone know how to set a defau ...

What is the purpose of the video-js endcard plugin incorporating native controls into the player?

Endcard is a unique plugin designed for the video-js html5 video player that adds clickable links to the end of a video. (More information on endcards can be found here: https://github.com/theonion/videojs-endcard). To implement an endcard, simply include ...