Bootstrap 5 Popover with HTML Content

Bootstrap 5 Popover with HTML Content
Code Snippet:simple popover
Author: Mert Cukuren
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 2,211
License: MIT
Edit Code online: View on CodePen
Read More

This code provides a convenient way to create popover with HTML content using Bootstrap 5. By attaching event listeners to anchor tags (<a>), the code enables the display of custom HTML content when the user hovers over the links.

Basically, this popover is based on Vanilla JavaScript which intelligently calculates the position of the popover to ensure optimal visibility. It is compatible with Bootstrap 5 projects and suitable for dependency-free applications as well.

Additionally, the JS code includes functions to handle mouseover, mouseleave, and mousemove events, allowing the popover to appear, disappear, and update its position accordingly. The purpose of this code is to enhance user experience by providing interactive and informative popovers that can be easily integrated into web applications/websites.

How to Create Popover with HTML Content in Bootstrap 5 Projects

1. First of all, load Google Fonts (optional), Normalize, and Bootstrap 5 CSS by adding the following CDN links into the head tag of your webpage.

<link href="https://fonts.googleapis.com/css?family=Cookie|Karla:400,700" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

2. To create a popover with customized HTML content, simply add the data-hover-content attribute to the HTML anchor element and place your desired content within the attribute value.

This content will be rendered inside the popover and displayed when the hover event is triggered. Feel free to add this attribute to multiple elements on a single page, as demonstrated on the demo page.

<a href="#" data-hover-content="<div class='hover-content'>
    <img src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/344846/500px-P1040705_copyGemeentehuis_Zundert.jpg' />
    <p>Zundert is a municipality and town in the south of the Netherlands, in the province of North Brabant.</p>
    </div>">Zundert, Netherlands</a>

3. Now, use the following CSS code to style the popover. Modify the CSS properties and values as needed to achieve the desired visual effect.

.hover-content {
  padding: 10px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
  background-color: #fff;
  width: 240px;
}

[data-hover-wrapper] {
  transition: opacity 0.3s, transform 0.3s;
}

.hover-content > img {
  max-width: 100%;
  margin-bottom: 10px;
}

.hover-content > p {
  font-size: 14px;
  margin: 0;
  line-height: 1.4;
}

.info {
  position: fixed;
  bottom: 0;
  right: 0;
  background-color: #000;
  padding: 10px 20px;
  color: #fff;
  font-size: 13px;
}

4. To activate the popover functionality, add the following JavaScript code just before the closing </body> tag. This code enables popovers using Vanilla JS, making it compatible with Bootstrap 5 projects. However, it can also be used in dependency-free projects:

const links = document.getElementsByTagName("a");

[...links].forEach(link => {
  link.addEventListener("mouseover", handleMouseOver);
  link.addEventListener("mousemove", handleMouseMove);
  link.addEventListener("mouseleave", handleMouseLeave);
});

function handlePosition(e) {
  const ID = e.target.getAttribute("data-hover-id");
  const wrapper = document.getElementById(ID);
  let top = "";
  if (
  !(e.target.getBoundingClientRect().top + wrapper.offsetHeight > innerHeight))
  {
    top = `${e.clientY + e.target.offsetHeight}px`;
  } else {
    top = `${e.clientY - (wrapper.offsetHeight + e.target.offsetHeight)}px`;
  }

  return `position: fixed; left: ${e.clientX -
  wrapper.offsetWidth / 2}px; top:${top}`;
}

function handleMouseOver(e) {
  const hoverContent = e.target.getAttribute("data-hover-content");
  const ID = Math.random().
  toString(36).
  substr(2, 9);
  const wrapper = document.createElement("DIV");
  e.target.setAttribute("data-hover-id", ID);
  wrapper.setAttribute("data-hover-wrapper", "");
  wrapper.setAttribute("id", ID);
  wrapper.setAttribute("style", "opacity: 0; transform: scale(.8)");
  wrapper.innerHTML = hoverContent;
  document.body.append(wrapper);
  wrapper.setAttribute("style", handlePosition(e));

  // You can remove this line when you are using. I had added for the demo.
  if (document.querySelector('.info')) document.querySelector('.info').remove();

}

function handleMouseLeave(e) {
  const ID = e.target.getAttribute("data-hover-id");
  document.getElementById(ID).style.opacity = 0;
  document.getElementById(ID).style.transform = "scale(.8)";
  setTimeout(() => {
    document.getElementById(ID).remove();
  }, 150);
}

function handleMouseMove(e) {
  const ID = e.target.getAttribute("data-hover-id");
  const wrapper = document.getElementById(ID);
  wrapper.setAttribute("style", handlePosition(e));
}

window.addEventListener('scroll', () => {
  const wrapper = document.querySelector('[data-hover-wrapper]');
  if (wrapper) wrapper.remove();
});

That’s it! hopefully, you have successfully created a Bootstrap 5 popover with HTML content! If you have any questions or suggestions, please feel free to comment below. I’m here to help and assist you further.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X