When hovering over an image to show a text box using JavaScript, it only works on one image due to the use of getElementById

I have been experimenting with some JavaScript code to create a pop-up box that appears when you hover over images. However, I have encountered an issue where it only works for one image. I suspect this is because I have used IDs instead of classes, but I'm not entirely sure. Here is the code snippet I have written:

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'inline';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

HTML

<img id="parent" src="img/Fruits.png" alt="Fruit">
                    <div id="popup">
                        <h5>
                            Apple:
                        </h5>
                        <h5 class="fruitDescription">
                            Apples taste good
                        </h5>
                    </div>

CSS

#popup {
display: none;
position: absolute;
background: #000;
opacity: 0.85;
border-radius: 5px;
width: 500px;
height: 382px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
margin-top: -105px;
margin-left: 40px;
color: #1E90FF;
}

#popup:before{
content: "";
position: absolute;
top: 60px;
left: -25px;
z-index: 1;
border: solid 15px transparent;
border-right-color: black;
color: #1E90FF;
}

I suspect the issue lies with using IDs in my code. I am currently exploring ways to achieve the same functionality for multiple images.

Thank you.

Answer №1

Forget about using javascript, simply add a class to img/popup and wrap it up like this

.wrap {
  position: relative;
}
.popup {
  display: none;
  position: absolute;
  background: #000;
  opacity: 0.85;
  border-radius: 5px;
  width: 500px;
  height: 382px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  margin-top: -105px;
  margin-left: 40px;
  color: #1E90FF;
  z-index: 1;
}
.popup:before{
  content: "";
  position: absolute;
  top: 60px;
  left: -25px;
  z-index: 2;
  border: solid 15px transparent;
  border-right-color: black;
  color: #1E90FF;
  pointer-events: none;
}
.pic {
  z-index: 0;
}
.pic:hover + .popup {
  display: block;
}
<div class="wrap">
  <img class="pic" src="http://lorempixel.com/50/50/nature/1/" alt="Fruit">
  <div class="popup">
    <h5>
      Apple:
    </h5>
    <h5 class="fruitDescription">
      Apples taste good
    </h5>
  </div>
</div>

<div class="wrap">
  <img class="pic" src="http://lorempixel.com/50/50/nature/2/" alt="Fruit">
  <div class="popup">
    <h5>
      Lemon:
    </h5>
    <h5 class="fruitDescription">
      Lemon is sour
    </h5>
  </div>
</div>

Answer №2

When all your images have the same ID, it causes a problem because IDs must be unique within the entire document. The getElementById function will only return one element, assuming you are following the standard. To assign the onclick event to multiple elements, you should consider switching to using a class instead.

Answer №3

If you're familiar with jQuery, you can easily manage multiple images by converting your ids to classes.

$('.parent').on('mouseover', function(){
    $(this).next('.popup').css('display', 'inline');
});

$('.parent').on('mouseout', function(){
    $(this).next('.popup').css('display', 'none');
});

For a demonstration, check out this example: https://jsfiddle.net/dfurg918/

Answer №4

Check out this solution using JavaScript:

document.querySelectorAll(".imageContainer").forEach(function(element) {
  element.onmouseover = function() {
    element.querySelector('.popup').style.display = 'block';
  };
  element.onmouseout = function() {
    element.querySelector('.popup').style.display = 'none';
  };
});
.imageContainer .popup {
  display: none;
  position: absolute;
  background: #000;
  opacity: 0.8;
  border-radius: 8px;
  width: 450px;
  height: 352px;
  margin-top: -90px;
  margin-left: 35px;
  color: #FF4500;
}
.imageContainer .popup:before {
  content: "";
  position: absolute;
  top: 50px;
  left: -20px;
  z-index: 1;
  border: solid 12px transparent;
  border-right-color: black;
  color: #FF4500;
}
<div class="imageContainer">
  <img id="image1" src="img/Animals.png" alt="Cute Animals">
    <div class="popup" id="popup1">
        <h5>
            Dog:
        </h5>
        <h5 class="animalDescription">
            Dogs are loyal companions
        </h5>
    </div>
</div>
<div class="imageContainer">
  <img id="image2" src="img/Plants.png" alt="Green Plants">
    <div class="popup" id="popup2">
        <h5>
            Tree:
        </h5>
        <h5 class="plantDescription">
            Trees produce oxygen
        </h5>
    </div>
</div>

Answer №5

It has been noted by others that the id attribute should be unique for each element while the name attribute can be shared among elements. This allows for the use of document.getElementsByName() to access multiple elements.

PLEASE NOTE: When using getElements ByName, remember the 's'.

Another option is to use document.querySelector() and document.querySelectorAll() to target specific elements based on selectors like element type, class, name, attribute existence, attribute value, and more. jQuery, with its slightly different syntax, can achieve similar results to querySelector[All]().

With one of the above methods, you can select elements and bind the mouseover and mouseout events to them.

Here is an example of how this could be implemented:

  1. Change id='parent' to name='parent'.
  2. Select all elements with attribute name='parent'.
  3. Attach events to each element in the set.

(function() {
  var parents = document.querySelectorAll('img[name="parent"]');

  function alertMe() {
    alert('click is bound');
  }

  for (var i = 0; i < parents.length; i++) {
    parents[i].onclick = alertMe;
  }
})();
<img name="parent" src="img/Fruits.png" alt="Fruit&quot;">
<div id="popup">
  <h5>
                            Apple:
                        </h5>
  <h5 class="fruitDescription">
                            Apples taste good
                        </h5>
</div>
<img name="parent" src="img/Fruits.png" alt="Fruit&quot;">
<div id="popup">
  <h5>
                            Banana:
                        </h5>
  <h5 class="fruitDescription">
                            Bananas taste better
                        </h5>
</div>

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

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...

What are the steps to ensure that CSS3 animations function properly in Outlook 2013?

Is it possible to incorporate CSS3 animations into an email signature in Outlook 2013? I've tried adding them, but they don't seem to be working. Can anyone provide guidance on how to make CSS3 animations function properly in Outlook 2013? ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Change in ReactJS URLs without causing the entire page to refresh when using BrowserRouter

After conducting extensive research and struggling for a solution for quite some time, it appears that I am facing an issue with my ReactJS project. As a beginner in ReactJS, I have developed a game (a quiz) with multiple levels where the component remains ...

What is the process for including or excluding a class from a horizontal scrollbar?

I've been trying to implement a back to top button on a horizontally scrolling page. However, I'm encountering difficulties in adding or removing the necessary class to show or hide the button. Here's the JavaScript code I'm using: $( ...

What's the best way to implement image size and type validation, specifically for .jpg and .png files, using Multer?

When using multer to receive files from the FrontEnd, I need to validate the image size to ensure it's less than 1MB. Additionally, I want to restrict the accepted file types to .jpg, .jpeg, and .png only. const multer = require("multer"); c ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Unable to conceal adjacent radio buttons

My challenge is to use only HTML and CSS, without JavaScript, to show the first radio button with its label initially. When a user clicks on it, the second radio button and label should appear while the first disappears, and so on. I am struggling to ach ...

Tips for positioning Bootstrap form labels and input fields in alignment

Currently, I am enhancing bootstrap-4 forms that consist of multiple input fields and labels. The form is functional, but I aim to elevate its visual appeal and user-friendliness. Working Snippet <link rel="stylesheet" href="https://stackpath.bootst ...

When enlarging or extending the container, text starts to spill out

My issue is that the text content is overflowing the designated box or container - any ideas on how to fix this problem? I have attempted to utilize max-width and max-height, but unfortunately, I am unable to get them to function as intended. Here's ...

Finding the earliest and latest dates from an event list in Angular can be accomplished by sorting the dates and

Can someone help me find the earliest and latest date from the list of events? Below is the code snippet along with a screenshot of the console log message. events: Event[] = []; count=0; minDate = new Date(); maxDate = new Date(); constructor(pr ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

Would it be beneficial to upload and download an image using the same ajax call?

I recently made a change to my web app's image upload feature. Previously, the process involved uploading an image, retrieving the image URL, and then making a second request to download the image from the URL. Now, I have streamlined it so that when ...

Enhancing the appearance of React Native components by incorporating borderColor results in the emergence of

In my current React Native project, there is a profile component that includes the following design: https://i.sstatic.net/URrN6.png The profile container is styled with a backgroundColor of '#fff', and the pencil icon has a borderColor of &apo ...

Is it necessary to include the Fonts file (which accompanies Bootstrap files) in the HTML document?

As a beginner in HTML, I decided to incorporate Bootstrap into my project. After downloading the necessary files, including css, js, and fonts, I found myself able to easily add the css and js files using the appropriate tags. However, I encountered some c ...

What is the process for applying a filter to a background image within the body of a webpage?

I'm attempting to apply a filter to the background image of the body element. Currently, I have implemented the following code: body { background: url("/img/congruent_pentagon.png"); color: white; font-family: "Raleway"; -webkit-filte ...

Implement a vertex shader to transform a mesh's vertices without consideration of its current location

Looking to add movement to my meshes using a vertex shader, I've run into an issue where translating my meshes in the scene also affects the position of a sinus wave. The goal is to keep the sinus wave consistent across both meshes even when translati ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...