Ways to distinguish between popovers using identifiers or classes

I'm encountering an issue where I have two popovers, each containing HTML content.

Below is the code snippet:

<button class="count" data-toggle="popover">+click me</button>
<div  class="popover_content_wrapper" style="display: none">
  <p>Rahul</p>
</div>

<button class="count" data-toggle="popover">+click me</button>
<div  class="popover_content_wrapper" style="display: none">
  <p>Dravid</p>
</div>

In my JavaScript section:

  $(function() {
    $('[data-toggle="popover"]').popover({ html : true,
        content: function() {
            return $('.popover_content_wrapper').html();
        }
    })
  })

When I click the first button, it works correctly and displays "Rahul" in the popover.

However, clicking the second button also shows "Rahul" instead of "Dravid". I need it to display "Dravid" when the second button is clicked.

Answer №1

Click on $(this) to reveal the content:

$(function() {
  $('[data-toggle="popover"]').popover({
    html: true,
    content: function() {
      return $(this).next().text(); // or .html();
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3c3dcc3c3d6c19dd9c0f3829d82859d83">[email protected]</a>/dist/umd/popper.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>


<button class="count" data-toggle="popover">+click me</button>
<div class="popover_content_wrapper" style="display: none">
  <p>Rahul</p>
</div>

<button class="count" data-toggle="popover">+click me</button>
<div class="popover_content_wrapper" style="display: none">
  <p>Dravid</p>
</div>

Answer №2

Simply utilize $(this).next() because it is the immediate next div after the clicked button.

$(function(event) {
    $('[data-toggle="popover"]').popover({ html : true,
        content: function() {
            return $(this).next('.popover_content_wrapper').html();
            // or $(this).next().html()
        }
    })
  })
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<button class="count" data-toggle="popover">+click me</button>
        <div  class="popover_content_wrapper" style="display: none">
             <p>Rahul</p>
         </div>

<button class="count" data-toggle="popover">+click me</button>
        <div  class="popover_content_wrapper" style="display: none">
             <p>Dravid</p>
         </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

JavaScript code for displaying and concealing elements

I have a simple requirement where I need to check for a variable and display or hide a class based on its value. This is being done on a SharePoint publishing page. The snippet below is not working as expected: if (source === 'show') { $(&a ...

Simple organization of a table by sorting one column in a descending direction, all without the need for any additional plugins

Currently, I am working with a simple table containing several columns. My task involves sorting the table based on the values in the first column, which are integers. The sorting should only occur once and in descending order. I need to accomplish this ...

Tips for preventing ng bootstrap dropdown from changing when the enter key is pressed in any input field in Angular 13

I have encountered an issue with the Angular-powered bootstrap dropdown. Whenever I press the enter key in the input field, it always changes the dropdown value to the first option. Check out the demo here HTML: <div class="row mb-3 mt-3"> ...

Jquery If Block Troubleshooting: Identifying and Resolving

const response = fetch("./viewforms", { method: "GET", async: false }).then(response => response.text()); response.then(data => { const myObject = JSON.parse(data); alert(myObject.attributes[0]["type"]); $("#updateDiv1").htm ...

Ways to send a notification every time there is a modification in the back-end data?

We are dealing with a simple JSON structure like the following: { name: "Johnson" } My strategy involves utilizing AJAX to display the name as shown below: $.ajax({ url: /info.json, success: function(data) { $('<span><b ...

Implementing Angular to activate the JavaScript 'click' event

I am attempting to initiate an 'onclick' event within an angular controller. <div id="galerie"> <h2>{{main.Page.title()}}</h2> <hr> <div class="row"> <div class="col-sm-4 col-xs-6" ng-repeat= ...

Angular's use of ES6 generator functions allows for easier management of

Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far: function loadPosts(skip) { return $rootScope.spawn(function *() { try { let promise = yield User.findAll(); $time ...

Solving yarn conflicts when managing multiple versions of a package

My software application contains a vulnerability related to a package that has different versions available (1.x, 2.x, 3.x). Since many other packages rely on this particular one as a dependency, updating each one individually is not a viable solution at t ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

The art of rotating PDF files and various image formats

Looking for a way to rotate PDF and image files displayed on an HTML page using jQuery. I attempted: adding a CSS class - without success. Here is an example code snippet: .rotate90 { webkit-transform: rotate(90deg); moz-transform: rotate(90de ...

What is the best way to stack two pull-right elements on top of each other within the Bootstrap grid system?

I have set up a bootstrap grid system on my webpage and I am trying to align two elements to the right, one below the other. Currently, this is how it appears: https://i.sstatic.net/UcpAJ.png When I try to align the "Active" and "Primary" buttons undernea ...

React component that enables radio inputs to repeat upon selection

My current project involves creating a quiz app where users can answer single questions using React on Codepen. I am utilizing an API to fetch a question, along with 3 incorrect answers and 1 correct answer, then storing them in the app's state. Howev ...

Using Three.js to parse a JSON string

When working with three.js... I am aware of the JSONLoader for loading JSON from a file or URL. However, I am wondering if it is possible to directly load a JSON object that is already in the current file? For example, if I have a mesh stored in a JSON o ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

The Canvas renderer in Three.js is struggling to properly utilize the map and color properties

While attempting to utilize both the map and color properties at the same time with the canvas renderer, I have encountered a problem where only one of them will work properly. Additionally, when the cube to which the image is applied rotates, the image ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

Import css background-images from a separate local directory that is located outside the root directory of the Next JS

I am facing a challenge with hosting a next.js app within the file structure of a parent website. I need the CSS in the app to use images that are located outside the app's file structure but within the parent website's file structure. Here is a ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...

The functionality of Css translate is not functioning as expected

I'm experiencing an issue with the translation of a tooltip. It's supposed to appear and then translate upwards, but in my code it only appears... I can't figure out what's wrong in my code... Any ideas please? View demo: http://jsfidd ...