Positioning a Bootstrap popover directly adjacent to the cursor's location (within the clicked element)

I've been struggling to get my bootstrap popover to show up inside the element I'm calling it on, next to my mouse cursor. Despite extensive research in the popper.js documentation and numerous attempts with various parameters, including the 'offset' modifier, I can't seem to make the popover appear where I want it to.

Here's an example of what I've tried so far, aiming for the popover to appear near the mouse click within a large div:

$(".a_large_div").click(function(e) {
    var relX = e.pageX - parentOffset.left;
    var relY = e.pageY - parentOffset.top;
    var height = $('.popover').height();
    $(this).popover({
        placement: 'top',
        offset:'-'+(relX + 1000)+'px,-'+(relY)+'px',
        title: 'My Popover', 
        html:true,
        trigger: 'manual',
        modifiers: {
            flip: { enabled: false },
            inner: { order: 700, enabled: true },
            applyStyle: { order: 900, enabled: true, fn: (data, options) => 
                { 
                     data.styles.left = "1000px";
                     console.log(data, options);
                     return data;
                }   
            },
            offset: { order: 0, enabled: true, offset: '-'+(relX + 1000)+'px,-'+(relY)+'px'  },
            },   
            boundary: this,
            content: function() {return $("#my_popover_content").html();},
            delay: 100
    }).on('show.bs.popover', function() {
        // execute some code
    }).on('shown.bs.popover', function() {
        // execute some code
    }).on('inserted.bs.popover', function() {
        Object.assign($('.popover')[0].style,{left:""+relX+"px !important",top:""+relY+"px !important"});
    }).on('hidden.bs.popover', function() {
        // execute some code
    }).on('hide.bs.popover', function() {
        // execute some code
});

$(this).popover('toggle'); 

$('.popover').css('left', (relX) + 'px');
$('.popover').css('top', (relY) + 'px');

Despite trying various positioning methods, the 'placement' modifier seems to dominate all others, leaving me unsure of how to override its positioning during the popper.js update process. Any help would be greatly appreciated.

Answer №1

Reflecting on this particular question, it's clear that I fell into the trap of trying to do too much at once. Juggling multiple tasks made it difficult to focus on isolating a specific functionality for building and testing.

I decided to revisit this issue as I've come to realize that the solution is actually quite straightforward.

To position a Popover element absolutely and display it upon click, you can set the 'left' and 'top' CSS values based on the x and y coordinates provided by the click event object.

var data=[
  {"x":10,"y":10,"height":100},
  {"x":120,"y":10,"height":120},
  {"x":230,"y":10,"height":150},
  {"x":340,"y":10,"height":180},
  {"x":450,"y":10,"height":200}
];


var bar = d3.select("#barchart").append("svg")
.attr("width",1000)
.attr("height",250)
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x",function(d){return d.x }) 
.attr("y",function(d){return 250 - d.height})
.attr("width",90)
.attr("height",0)
.on('click', function() {
  var left = d3.mouse(this)[0];
  var top = d3.mouse(this)[1];
  var theHeight = $('.popover').height();
  $('.popover').show();
  $('.popover').css('left',(left+10)+'px');
  $('.popover').css('top', (top-(theHeight/2)-10)+'px');
  })
.style("fill","blue")
.transition()
.duration(4000)
.attr("height",function(d){return(d.height)});
.popover {
    position:absolute;
    display:none;
    background:#fff;
    border: 1px solid #999;
    padding:10px;
    width:auto;
    box-shadow:0 0 10px rgba(0, 0, 0, .5);
}
.popover:after, .popover:before {
    right: 100%;
    border: solid transparent;
    content:" ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}
.popover:after {
    border-color: rgba(255, 255, 255, 0);
    border-right-color: #ffffff;
    border-width: 10px;
    top: 50%;
    margin-top: -10px;
}
.popover:before {
    border-color: rgba(201, 201, 201, 0);
    border-right-color: #c9c9c9;
    border-width: 11px;
    top: 50%;
    margin-top: -11px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="barchart"></div>
<div class="popover">
  <p>hello world</p>
</div>

https://codepen.io/modularmoon/pen/gOLooeb

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

Filter should be applied solely if the input exceeds 3 characters in length

Is there a way to display the results of an ng-repeat with a filter based on input length being greater than 3 characters? I attempted the following code (filter: input.length > 3): <input type="text" ng-model="input" placeholder="Search"> < ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

Transforming React Redux reducer to hooks for a more modern approach

I am in the process of creating a login and registration application. I need to change a reducer that is currently being used for a class-based component to work with hooks instead. Here is the existing reducer: import { SET_CURRENT_USER, USER_LOADING } fr ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

Gleaming R: Warning prompt or modal box input: invalid

In the process of developing a basic application, I am seeking to implement a pop-up notification for invalid inputs. By referencing the suggestion provided in #1656, I have come up with an example that introduces a visually appealing background color when ...

extract specific data from JSON using JavaScript

Dealing with JSON data can be tricky, especially when working with multiple sets of information to choose from. When I inspect the data in my JavaScript code using console.log(contacts.data["all"]);, I can see the returned objects clearly. Here's a ...

The ul element is not being properly styled by the CSS pseudoclass :checked

I recently attempted to create a responsive navigation bar using a YouTube tutorial that utilizes a checkbox to display and hide the menu on smaller screens. Despite meticulously following the tutorial and testing different browsers such as Chrome, Edge, a ...

What is the appropriate way to link the right function to the slideshow button?

I'm having trouble creating a functional slideshow with buttons. Each button should display its corresponding div when clicked, while the slideshow continues to function as normal. View the demo here: http://jsfiddle.net/sabeti05/dsagcc5u/ HTML ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

What are some strategies for handling data after it has been retrieved using Axios?

In my current project, I am working with MySQL database and fetching data using Axios and a useEffect hook. Once the data is retrieved, I pass it to a component as a prop. Here's how: const Component = () => { //Database URL const urlProxy = &q ...

JavaScript CheckBox Color Change Not Functioning

Hello, I am currently experimenting with the checkAll function. When I click on the checkAll checkbox, it should select all rows and change their background color accordingly. Below is the JavaScript code I am using: function checkAll(objRef) { v ...

Using SignalR for lengthy processes: transmitting progress updates

Utilizing SignalR to initiate lengthy computations on the server and notify the client when the results are ready. The input bindings consist of an HTTP request. Desire to send multiple messages to update the client on various stages of the process (e.g., ...

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

Navigating AJAX Pages - Maximize the Potential of #home and Other Sections

I am working on creating AJAX pages using a tutorial I found on Tutorialzine. The script I am using loads pages using AJAX but it requires specifying the page number in the URL like http://example.com/#page1 or http://example.com/#page2. Is there a way t ...

Utilizing a specialized xyz tileLayer to specifically highlight a designated area on the map

I am looking to add the xyz tile layer from this link onto a leaflet map: http://weatheroo.net/radar/data/2019/07/15/18/40/{z}/{x}/{y}.png This particular weather radar composite is focused on Germany, hence why it only covers middle Europe. The specifie ...

Disable the div by graying it out when the button is clicked

In my jsni form, I have implemented a click handler on the save button. When the save button is clicked, I would like the specific div to be greyed out to indicate that data is being saved. var x=$doc.createElement("div"); x.id="nn"; var lbl=$doc.createEl ...

What is the best way to establish a header in the login route that allows the browser to remember the user's login status?

I have successfully implemented a user login backend and everything seems to be working fine. However, when I try to access a user detail after logging in, I am faced with an authorization issue preventing me from exploring other routes. How can I store th ...

Unable to center text in a Bootstrap 4 div

Hello everyone, I have come across this code snippet: <div class="row mt-5" id="System Requirements"> <div class="col-4"> <h4 class="text-nowrap font-weight-bold pl-4">System Requirements</h4> </d ...

Guide on incorporating an inline input and glyph icon within a table cell using Bootstrap 3

How do I align my glyph icon in the same line as an input in Bootstrap3? I've tried various classes but none seem to work. The glyph icon keeps displaying on a separate line because the input is too long. The only solution that works is manually setti ...