Choose a div using jQuery and activate a hidden div

Seeking assistance in creating an interactive infobox that appears when hovering over a related image. Currently, the infobox pops out and flashes, but there is a problem where it shifts away from the image during the hover.

I attempted to only display the infobox when hovering over the image using .mouseenter and FadeIn instead of fadeToggle. However, I encountered a bug that causes the infobox to appear every other time the image is hovered over.

Here's my code (includes NodeJS - EJS extension):

HTML:

 <section class="campview">
        <h1>Most Popular Campgrounds</h1>
          <hr>
           <div class="container-fluid">
               <div class="row">
                  <%  for(var i=0 ; i<4 ; i++){ %>
                    <div class="col-xs-12 col-sm-3">
                        <img src="<%=campgrounds[i].image%>" class="image-responsive img-rounded animated fadeIn">
                           <div class="infopop">
                               <div class="row">
                                  <div class="col-xs-12 col-sm-12">
                                     <h3><%=campgrounds[i].name%> </h3>
                                      </div>
                                  </div>
                             <div class="row">
                                  <div class="col-xs-7 col-sm-7">
                                       <p class="vert-center"><%= campgrounds[i].description.slice(0,100)+"..." %></p>
                                  </div>
                                  <div class="col-xs-5 col-sm-5">
                                     <a href="/campgrounds/<%=campgrounds[i]._id%>" class="btn btn-primary">Read More</a>
                                  </div>
                            </div>
                         </div>
                   </div>
                 <% }; %>

                </div>
              <div class="row">
                  <div class="col-xs-12">
                     <a class="pull-right" href="/campgrounds">View all campgrounds</a>
                  </div>
              </div>
            </div>
   </section>

CSS:

.infopop{
    display: none;
   z-index: 1;
   position: absolute;
   top: 57%;
   width: 92.8%;
   height: 40%;
   background-image: -webkit-gradient(
        linear, left top, left bottom, from(rgba(50,50,50,0)),
        to(rgba(50,50,50,0.8)), color-stop(.3,#000)
     );
}

Jquery:

$(document).ready(function() {
  $(".campview img").hover(function(event){
              $(this).next().fadeToggle("fast");
     });
});

Your understanding and guidance would be greatly appreciated! Thanks!

Answer №1

To enhance functionality, consider utilizing a class to detect if the next item is open and apply a "mouseleave" event to eliminate reliance on $(".campview img") while the image remains open.

Below is a functional code snippet. I enclosed your img and .infopop within their own container labeled .camp-block

$(document).ready(function() {
 
   $(".camp-block img").on("mouseenter", function(event) {
 
     event.stopImmediatePropagation();

     var $myNext = $(this).next();
     if (!$myNext.hasClass("isOpened")) {
       $myNext.addClass("isOpened");

        $myNext.bind("mouseleave", function(ev) {

         $(this).removeClass("isOpened").unbind("mouseleave")

       }); 
     }
   });
 })
.camp-block {
  width: 94%;
  margin: 0 3%;
  position: relative;
}

.camp-block img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 2;
}

.camp-block .infopop {
  position: relative;
  z-index: 1;
  display: inline-block;
  width: 100%;
  padding-top: 50%;
}
.camp-block .infopop.isOpened{
  z-index: 3;
}
.camp-block .infopop.isOpened .bottom-block{
  opacity: 1;
  transition: opacity 0.2s ease-in-out;
}

.camp-block .infopop .bottom-block {
  opacity: 0;
  transition: opacity 0.2s ease-in-out;
  color: #fff;
  width: 100%;
  display: inline-block;
  border-bottom-right-radius: 6px;
  border-bottom-left-radius: 6px;
  background-image: -webkit-gradient( linear, left top, left bottom, from(rgba(50, 50, 50, 0)), to(rgba(50, 50, 50, 0.8)), color-stop(.3, #000));
}


}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<section class="campview">
  <h1>Most Popular Campgrounds</h1>
  <hr>
  <div class="container-fluid">
    <div class="row">

      <div class="col-xs-12 col-sm-3">
        <div class="camp-block">
          <img src="https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg" class="image-responsive img-rounded animated fadeIn">
          <div class="infopop">
            <div class="bottom-block">
              <h5>custom headline 1</h5>
              <p>
                some text
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="col-xs-12 col-sm-3">
        <div class="camp-block">
          <img src="https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg" class="image-responsive img-rounded animated fadeIn">
          <div class="infopop">
            <div class="bottom-block">
              <h5>custom headline 2</h5>
              <p>
                some text
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="col-xs-12 col-sm-3">
        <div class="camp-block">
          <img src="https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg" class="image-responsive img-rounded animated fadeIn">
          <div class="infopop">
            <div class="bottom-block">
              <h5>custom headline 3</h5>
              <p>
                some text
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="col-xs-12 col-sm-3">
        <div class="camp-block">
          <img src="https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg" class="image-responsive img-rounded animated fadeIn">
          <div class="infopop">
            <div class="bottom-block">
              <h5>custom headline 4</h5>
              <p>
                some text
              </p>
            </div>
          </div>
        </div>
      </div>



    </div>
    <div class="row">
      <div class="col-xs-12">
        <a class="pull-right" href="/campgrounds">View all campgrounds</a>
      </div>
    </div>
  </div>
</section>

Enhancements Explained

I restructured the layout by enclosing img and .infopop within .camp-block to maintain the spacing provided by bootstrap's classes such as .col-sm-*, which adds padding.

Additionally, I applied position:relative to .camp-block so that I could use position:absolute for the img tag.

Ordering Elements

Initially, when entering the site, elements must have a default position. The img should be on top (z-index:2) of .infopop (z-index:1) to allow jQuery to trigger the mouseenter event.

Keep in mind that .infopop includes padding-top:50% to move

.bottom-block</code further down, and without the class <code>.isOpened
, .infopop will have an opacity of 0 via .bottom-block.

Using JQuery

On hovering over the image, jquery will add an .isOpened class to .infopop, changing its css z-index to 3. This shift places .infopop above the img and transitions .bottom-block's opacity to 1. A mouseleave event is bound to .infopop, allowing removal of the .isOpened class upon exiting the element, returning everything to its initial state.

Answer №2

Check out this alternative code:

  $(document).ready(function() {
      $(".campview img").hover(function(){
                  $(this).siblings('.infopop').css('display', 'block');
         }, function() {
                  $(this).siblings('.infopop').css('display', 'none');
        });
    });

Answer №3

.reveal {
   visibility: hidden;
   transition: visibility .25s ease-in-out;
   -moz-transition: visibility .25s ease-in-out;
   -webkit-transition: visibility .25s ease-in-out;
   }

   .reveal:hover {
      visibility: visible;
      }

Answer №4

In case anyone needs this solution in the future, I wanted to share my approach which I believe is one of the simplest possible. Essentially, I have set it up so that only the ".col" element containing the image will trigger the fadeOut action on the ".infopop".

Jquery

$(document).ready(function() {
  $(".infopop").hide();
  $(".campview img").mouseenter(function(event){
  $(this).next().fadeIn();
  });
  $(".campview div.col-xs-12.col-sm-3").mouseleave(function(event){
    $(".infopop").fadeOut();
  });

});

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

Raphael's path adorned with arrow-shaped tips

Recently delving into raphael.js, I am attempting to create an arrow head on a raphael path element (or draw an arrow from point A to point B). Here is the raphael path (line) that I have sketched from point A to point B on my canvas. Assuming that the val ...

What are the key principles of designing web and native mobile applications using React.js architecture?

I am intrigued by the idea of incorporating React.js for server-side rendering into my web service. However, I am facing a challenge when trying to transition from my current web service built with Express.js. At present, my web service caters to two platf ...

Transforming a React application from ES6 hooks to Class-based components

Hello, I am new to React and currently facing a challenge in converting the following code into a Class Based Component. Despite knowing that I am going in the opposite direction, I am unable to figure out how to proceed without encountering errors. Any ...

Replicating headers with Ajax and CodeIgniter

Hey there, I've encountered a rather peculiar issue that's got me stumped. I'm utilizing Codeigniter and Jquery for an ajax search feature. So far, everything seems to be functioning correctly and the data is being retrieved from my model a ...

What can I do to prevent my CTA image with a width of 100% from distorting when I change the height?

Creating a website and in need of a CTA image? Utilizing Bootstrap 4 along with custom CSS to tweak the appearance, I've set it to occupy the entire width of the screen using width: 100%;. As the screen size changes, the image remains responsive, adju ...

Crafting a captivating stacked image using just two segments

Recently, I designed my own personal website. To make it visually appealing, I decided to use a background picture as the header and placed my portrait as the avatar. My inspiration for the design was drawn from the sleek interface of Linkedin profiles. Ho ...

Is there a method for eliminating divs that have scrolled out of view on a never-ending webpage in order to prevent lag?

Looking for a solution to remove divs that have been scrolled past in Chrome in order to improve speed on an endlessly scrolling page. The sluggishness is making the page unusable. ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Embed array inside angular directive

In my angular application, I have a code snippet that generates a navigation tree within a <div>. The size of this tree depends on the contents of mymodule.tree.folders. To enhance this functionality, I want to create a directive named class="scrolla ...

Exploring the depths of a JSON structure using jQuery

This is my first time working with JSON data and I need some guidance on a specific issue. When using .getJSON on a local file, the structure appears neat like this: https://i.sstatic.net/7CYPC.jpg I can easily retrieve the value I want (CustRep) with c ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

Arranging images in a row with the help of :before and :after styling

Looking to use the pseudo selectors :before and :after to create a border around a div with images, but running into some issues. The :after image is not positioning correctly on the right side of the element and the text is dropping below the image. Check ...

TypeScript Error: Attempting to slice an undefined property - TypeError

In my Angular project, I have a csv file containing data that is imported along with the D3.js library: group,Nitrogen,normal,stress banana,12,1,13 poacee,6,6,33 sorgho,11,28,12 triticum,19,6,1 The TypeScript file includes code for displaying a stacked ba ...

Make sure to always display the browser scrollbar in order to avoid any sudden page

Question: How can I ensure the scrollbar is always visible in a browser using JavaScript? I've noticed that some of my web pages have a scrollbar while others do not, causing the page to jump when navigating between them. Is there a way to make t ...

Display a gradient-colored Bootstrap progress bar that visually represents the active width

I am trying to create a Bootstrap progress bar with a gradient color fill (such as red to green). Currently, my CSS code looks like this: .progress-lf { position: relative; height: 31px; background-color: rgba(51, 51, 51, 0.4) } .progress-lf ...

Modify the height of the panel-header in Bootstrap

I'm attempting to adjust the height of Bootstrap panel-header. However, when I modify the height using the following CSS code: style="height: 20px;" The title inside the header becomes misaligned. To see an example, check out this Plunker demo. Wh ...

What is the function of this program created with three.js?

I've been searching through various resources but I couldn't find any information on this new capsule. Although I understand the basics - that it creates a new capsule - I'm still unsure about the specific inputs required for it. Could someo ...

What is the process for verifying which classes have been assigned to a specific component?

I am working with a Vue component and I would like to determine, from within the component itself, which classes have been applied to it. Is there a way to accomplish this? Currently, I am using a workaround where I pass the class as a prop: <my-comp ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

The WebMethod isn't being triggered during debugging

Recently, I have been facing an issue while trying to insert data using jQuery. Previously, I had successfully performed this task, but after a long break, I encountered a problem. Upon debugging with the browser, I noticed that the Ajax call was not being ...