Place label at a set position when the mouse hovers over it

I need help creating a simple hover effect on a circle using jQuery. I'm facing an issue where the label location of the city overlaps with the circle when the mouse hovers over it. The label should be fixed in position on top of the red circle. Even when trying to describe a short-named city, the label overlapping remains unaddressed. For example:

const regionObject = {"philadelphia" : "Philadelphia",}

$(function(){


    $('circle').mouseenter(function(e){

        const circleId = $(this).attr('id');


      
        const regionObject = {
            "philadelphia" : "Philadelphia, a city in Pennsylvania",
                    }


        

            var div = $(`<div class="current_region">
            <div class="current_region_box">
            <p>${regionObject[circleId]}</p> 
            </div>
            <div class="region_pointer"></div>
            </div>`)
            .css({
                "display": "block",
                "left": (e.pageX - 40) + 'px',
                "top": (e.pageY - 45) + 'px'
            })
            .appendTo(document.body);

    
    }).mouseout(function(){
    $('body').find('.current_region').remove();
});


    
});
.current_region {
    position: absolute;
  }
  
  .current_region_box {
    position: relative;
    z-index: 10;
    border-radius: 30px;
    background: white;
    box-shadow: 0px 2px 6px 1px rgba(18, 40, 112, 0.5);
    padding: 4px 12px;
  }
  
  .current_region_box p {
    font-family: firagolight;
    font-size: 15px;
  }

  .current_region_box {
    position: relative;
    z-index: 10;
    border-radius: 30px;
    background: white;
    box-shadow: 0px 2px 6px 1px rgba(18, 40, 112, 0.5);
    padding: 4px 12px;
  }
  
  .current_region_box p {
    font-family: firagolight;
    font-size: 15px;
  }

  .region_pointer {
    position: absolute;
    z-index: 9;
    bottom: -9px;
    right: 3px;
    left: 0;
    margin: auto;
    width: 25px;
    height: 25px;
    background: white;
    border-radius: 5px;
    transform: rotate(45deg);
    box-shadow: 0px 0px 4px -1px grey;
  }
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <!-- Font Awesome -->
        <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    
        <!-- Developer CSS -->
        <link rel="stylesheet" type="text/css" href="./map.css">
        <!-- Jquery-->
        <script src="js/jquery-3.4.1.min.js"></script>
        
    </head>
    <body>
        <div class="example" style="text-align: center; padding-top: 50px; cursor: pointer; " >
            <svg height="100" width="100">
                <circle id="philadelphia" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"   />
                Sorry, your browser does not support inline SVG.  
              </svg>
        </div>


        

<!--Bootstrap JS-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity=" sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="./map.js"></script>
</body>
</html>

Answer №1

If you're looking for a CSS-only solution, try using the ::after pseudoclass to display a tooltip when hovering over an element. You can customize the position of the tooltip by adjusting the top and left properties.

body { margin: 50px }
#circle {
  width: 200px;
  height: 200px;
  background-color: red;
  border-radius: 50%;
  position: relative;
  border: 3px solid black;
}

#circle:after {
  content: "This is tooltip";
  position: absolute;
  top: -20px;
  left: 50%;
  display:none;
  
  /* these are just to make it prettier */
  background-color: black;
  padding: 10px;
  color: white;
  border-radius: 5px;
  opacity: .7; /* erase this if you dont want it transparent */
}

#circle:hover:after {
  display: block;
}
<div id="circle"></div>

To personalize the tooltip content, you can fetch the value from any attribute of the circle element, like title. Simply use: content: attr(title)

Answer №2

To utilize your code effectively, consider obtaining the center of the circle and utilizing the cx and cy attributes to position the label.

Furthermore, there seems to be a flickering issue when the mouse hovers over the label. To address this, include

.current_region{pointer-events:none;}
in CSS

$(function(){


    $('circle').mouseenter(function(e){

        const circleId = $(this).attr('id'); 
        const cx = Number($(this).attr('cx'));
        const cy = Number($(this).attr('cy'));

      
        const regionObject = {
            "philadelphia" : "Philadelphia, city in Pennsylvania",
                    }

            var div = $(`<div class="current_region">
            <div class="current_region_box">
            <p>${regionObject[circleId]}</p> 
            </div>
            <div class="region_pointer"></div>
            </div>`)
            .css({
                "display": "block",
                "left": (cx + 40) + 'px',
                "top": (cy - 20) + 'px'
            })
            .appendTo(document.body);

    
    }).mouseout(function(){
    $('body').find('.current_region').remove();
});


    
});
.current_region {
    position: absolute;
  }
  
  .current_region_box {
    position: relative;
    z-index: 10;
    border-radius: 30px;
    background: white;
    box-shadow: 0px 2px 6px 1px rgba(18, 40, 112, 0.5);
    padding: 4px 12px;
  }
  
  .current_region_box p {
    font-family: firagolight;
    font-size: 15px;
  }

  .current_region_box {
    position: relative;
    z-index: 10;
    border-radius: 30px;
    background: white;
    box-shadow: 0px 2px 6px 1px rgba(18, 40, 112, 0.5);
    padding: 4px 12px;
  }
  
  .current_region_box p {
    font-family: firagolight;
    font-size: 15px;
  }

  .region_pointer {
    position: absolute;
    z-index: 9;
    bottom: -9px;
    right: 3px;
    left: 0;
    margin: auto;
    width: 25px;
    height: 25px;
    background: white;
    border-radius: 5px;
    transform: rotate(45deg);
    box-shadow: 0px 0px 4px -1px grey;
  }
  
  .current_region{pointer-events:none;}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <!-- Font Awesome -->
        <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    
        <!-- Developer CSS -->
        <link rel="stylesheet" type="text/css" href="./map.css">
        <!-- Jquery-->
        <script src="js/jquery-3.4.1.min.js"></script>
        
    </head>
    <body>
        <div class="example" style="text-align: center; padding-top: 50px; cursor: pointer; " >
            <svg height="100" width="100">
                <circle id="philadelphia" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"   />
                Sorry, your browser does not support inline SVG.  
              </svg>
        </div>


        

<!--Boostrap JS-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity=" sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="    sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="./map.js"></script>
</body>
</html>

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

The URL requested exceeds the maximum length limit in asp.net, causing a 414 error

I encountered the issue of receiving an "HTTP Error 414. The request URL is too long." While reading through this article, I learned that it is caused by an excessively lengthy query string: Currently in my web.config, I have set maxQueryStringLength to " ...

Update Calendar Information Without Reloading the Entire Page

Is there a way to automatically refresh a div that includes a FullCalendar Calendar? I'm looking to refresh the div every 30 seconds to check for new data from the database without having to modify the ViewModel or reloading the page. index.html &l ...

how to target the last child element using CSS commands

<a><div class="myDiv"></div></a> <a><div class="myDiv"></div></a> <a><div class="myDiv"></div></a> <a><div class="myDiv"></div></a> // This specific one is what ...

Ways to alter formData using jQuery

For my form submission using AJAX, I utilize FormData to gather data. Here is how I collect the form's data: var data = new FormData($(this)[0]); One of the inputs on the form consists of a color value in HSV format that I need to convert to hex. Wh ...

Strategies and Methods for Assessing the Content and Organization of a Website

Seeking recommendations from the stackoverflow community for tools, techniques, and processes to analyze the structure and content of a moderately large, collaboratively edited website. The manual process is time-consuming, so automating it as much as poss ...

"Exploring the Differing Approaches of Ajax: Constructing

Considering StackOverflow's recommendation to ask a question rather than start a discussion, let's explore two methods using HTTPAsyncRquest to update a webpage without refreshing it: 1) Parsing/interpreting data returned by AsyncRequest to buil ...

Numeric input of 10 not recognized in the textbox

My validation for a textbox only accepts two digits, such as 11 or 12. However, it does not accept the digit 10. Check out my code snippet: <td width="60" height="20" class="case_txt" align="center"> <input type="text" onblur="CheckUnitValue ...

Activate Popover on Third Click with Bootstrap 4

Is it possible to create a button that triggers a popover after 3 clicks and then automatically dismisses after one click using Bootstrap v4.3.1? Code: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.mi ...

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

handsontable - personalized HTML button placed at the beginning of each row that performs an action when clicked

In my handsontable, I have successfully added a custom button in the 2nd column. When this button is clicked, I want to send the data of that particular row to the server for processing. I have written an onClick function for the button, but I am struggli ...

The information I input into this form is failing to be stored in the WAMP database

After implementing this PHP code, there are no error messages being displayed when I submit the HTML form. However, the data is not being added to the WAMP table. <?php error_reporting(E_ALL); ini_set('display_errors', 1); //$user_name = "roo ...

Issue with Javascript Promise causing failure to populate list with objects

app.get('/zones/:id/experiences', function(req,res) { var zone_key = req.params.id; var recent = []; var ref = firebase.database().ref('participants/'+zone_key+'/experiences'); ref.on("value", function(snapshot) { ...

"Utilizing Bootstrap 4: Understanding the Optimal Times to Implement the 'Row

After studying the fundamental guidelines for Bootstrap 4, a question has arisen in my mind: Under what circumstances should we utilize the .row class in our layout? I came across this example where the .row class was not used in the code. However, the ba ...

Checking for non-empty values in a jQuery UI DateRangePicker

tl;dr: How can I prevent empty dates from being inputted in jquery-ui-daterangepicker? I am currently utilizing the plugin and encountering difficulties in validating if a date range has been chosen. My objective is to keep the #export_date_range date ra ...

Encountering the error "object object" while attempting to pass parameters to my servlet through AJAX

Experiencing an issue where my ajax call is ending up in the error function. I have noticed that my success function is empty, but I was expecting to receive messages from my servlet whether the data provided is correct or incorrect. The popup dialog displ ...

Error message displayed: "Validator.elementValue is not a recognized function in JQuery Validation."

I am facing an issue with my form where I have two fields and I need at least one of them to be filled. I tried using a JQuery validate plugin but it seems that the require_from_group function is not working properly. Upon inspecting the console, I encoun ...

What is the best way to ensure that a canvas created using JavaScript spans 100% of the width?

Working with a canvas element generated by Javascript, see the code snippet below: http://jsfiddle.net/mtvzgnmm/ <div id="circle"></div> <script> $('#circle').circleProgress({ value: 0.75, size: 400, ...

Issue with Webpack: file-loader failing to load SVG files dynamically in HTML

Configuration in package.json: { "name": "webpackTutorial", ... "devDependencies": { "bootstrap": "^4.3.1", ... "webpack-merge": "^4.2.2" } } Webpack Configuration in webpack.common.js: var HtmlWebpackPlugin = ...

The remove() function is failing when attempting to add input fields dynamically

Hello, I am currently facing an issue with dynamically generating input fields based on AJAX results. Unfortunately, the .remove() function is not working as expected and my current solution involves repetitive code. Any guidance or assistance would be g ...

Using Golang to make an AJAX request and send data via a

My page has multiple fields that are not set up in a form because I want to be able to interact with them individually and use ajax to post the data. I am using Go to process the posted data. However, I am experiencing an issue where the data is being po ...