Annotation should be positioned above the span

JSFIDDLE

My task involves adding annotations to specific spans of text. Below is the code snippet:

HTML

<!DOCTYPE html>
<html> 
<head>  

    <link rel="stylesheet" href="css/demo.css" />

    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="js/demo.js"></script>
</head>
<body>
    <div class="dialog-container">
        <div class="annotation-head"></div>
        <div class="annotation-segment">
            <span class="marker" data-anno-id="0">This is a</span> 
            <span class="marker" data-anno-id="1">sample</span> 
            text
            <span class="marker" data-anno-id="2">another one</span> 
            text
            <span class="marker" data-anno-id="3">one mooooorreee</span> 
        </div>
    </div>  
</body>
</html>

Javascript

String.prototype.width = function(font) {

  var f = font || '12px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

$(document).ready(function() {

    var annos = ['first', 'second', 'third', 'forth']; // annotation data

    $('.marker').each(function () {
        var $t = $(this),
            pos = parseInt($t.attr('data-anno-id')),
            annoStr = annos[pos]; 

        // create an annotation for each marker
        var top = this.offsetTop - 5, 
            left = this.offsetLeft + ($t.width() - annoStr.width())/2,
            width = $t.width(),
            style = 'style="top:' + top + 'px; left:' + left + 'px;"';

        $('.annotation-head').append('<span class="anno label" ' + style + '>' + annoStr + '</span>');
    });
});

CSS

.dialog-container {
    width: 600px;
    height: 200px;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    border-radius: 10px;
    padding-left: 5px;
}

.annotation-head {
    padding-top: 7px;
}

.annotation-segment, .annotation-head {
    position: relative;
}

.marker {
    background: lightgreen;
}

.anno {
    position: relative;
    text-align: center;
}

.label {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;

    position: relative;
    display: inline-block;
    padding: 2px;
    font-size: 11.844px;
    font-weight: bold;
    line-height: 14px;
    color: #ffffff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
    white-space: nowrap;
    vertical-align: baseline;
    background-color: #999999;
}

I believe I'm close to achieving the desired outcome. However, due to using separate divs for annotations and text, the positioning of labels above the correct span is not consistent after the first annotation. Is there a way to calculate the accurate left offset for the labels without using

position: absolute
?

Answer №1

give this a shot

http://jsfiddle.net/jPYgM/6/

.dialog-container {
    width: 600px;
    height: 200px;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    border-radius: 10px;
    padding-left: 5px;
}

.annotation-head {
    padding-top: 7px;
}

.annotation-segment, .annotation-head {
    position: relative;
}

.marker {
    background: lightgreen;
}

.anno {
    position: relative;
    text-align: center;

}

.label {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;

    display: inline-block;
    padding: 2px 0 ;
    font-size: 11.844px;
    font-weight: bold;
    line-height: 14px;
    color: #ffffff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
    white-space: nowrap;
    vertical-align: baseline;
    background-color: #999999;
}

    String.prototype.width = function(font) {

  var f = font || '12px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

$(document).ready(function() {

    var annos = ['first', 'second', 'third', 'forth']; // your annotation data

    $('.marker').each(function () {
        var $t = $(this),
            pos = parseInt($t.attr('data-anno-id')),
            annoStr = annos[pos]; 
        var total_width=0;
        $('.annotation-head .anno').each(function(){
        total_width += $(this).width();
        })
        // create an annotation for each marker
        var top = this.offsetTop - 5, 
            left = this.offsetLeft -total_width,
            width = $t.width(),
                style = 'style="top:' + top + 'px; left:' + left + 'px;width:'+width +'px;"';

        $('.annotation-head').append('<span class="anno label" ' + style + '>' + annoStr + '</span>');
    });
});

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

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Difficulty encountered when attempting to load a template HTML with Flask and Jinja2 upon clicking

I am facing a challenge with understanding how Jinja templates are rendered. My goal is to send data to my Flask backend through a GET request, execute a query with that data as a parameter, and then display a Jinja child template with the retrieved inform ...

What causes the jQuery.easing error to happen when jquery-ui is being used?

After adding dependencies to achieve the add to cart effect in our project, I checked the package.json and found the following installed: "jquery": "^3.4.1", "jquery-ui": "^1.12.1", I then imported these into the co ...

Numbers do not automatically shift to a new line when reaching the fixed width limit

I have two <div>. In one of them, I have added 'Lorem ipsum' text, while the other contains numbers. I noticed that the div with numbers does not wrap the numbers to a new line within a fixed width <div>. Can anyone explain why number ...

"Use jquery to disable and gray out a text box, restricting it to read-only

Is there a way to change the color of a text box to grey and make it read-only when a checkbox is ticked? I have managed to make the text box read-only, but I can't figure out how to also turn it grey. Using the disabled attribute won't work in t ...

Positioning columns in Bootstrap with a fixed layout

Is there a way to troubleshoot issues with Bootstrap col? I attempted the following solution, but it's not yielding the desired outcome: <div class="row"> <div class="col-md-6">Content goes here...</div> <div class="col ...

What is the best way to choose all the options in a drop-down menu using Selenium Webdriver?

Currently, I am working with Selenium WebDriver and utilizing Java. In my application, there is a dropdown menu named Product containing multiple values (for example: 60). When running the code, I first deselect all options and then select the specific opt ...

The PHP random number generator appears to be malfunctioning when being compared to the $_POST[] variable

In this section, random numbers are generated and converted to strings. These string values are then used in the HTML. $num1 = mt_rand(1, 9); $num2 = mt_rand(1, 9); $sum = $num1 + $num2; $str1 = (string) $num1; $str2 = (string) $num2; The following code ...

AngularJS - enable user authentication to access exclusive content on the webpage without redirecting to a new page

I'm struggling with implementing a login form on my AngularJS site... My goal is to dynamically load a login form onto any page of the site without needing to navigate away, then asynchronously handle user login information and display a success or f ...

Error: Unable to access the property 'fontSize' as it is undefined

<!DOCTYPE HTML> <html> <head> <title>Interactive Web Page</title> <link id="mycss" rel="stylesheet" href="mycss.css"> <script> function resizeText(size) { va ...

What seems to be causing my "Rock Paper Scissors" application to malfunction and repeatedly crash my browser?

My assignment on "Rock Paper Scissors" required specific diameters to be used, but unfortunately, it's not functioning properly. Instead of displaying any output on the console, the page fails to load at all. Initially, I had all the strings appearin ...

Is there a way to direct video links specifically to a single iframe on a webpage?

I have an iframe and some links. I would like it so that when I click a link, the iframe is updated. echo "<iframe name='vidframe' width='100%' height='360px' src='http://vidto.me/embed-3t83y76l81ml-640x360.html& ...

Challenges arising from automatically directing users to a webpage following a successful Paypal transaction

I am currently working on a website project that involves utilizing python, flask, html, css, and js. One of the main functionalities of the site is to require a Paypal payment in order for users to input information. I have successfully implemented a feat ...

Every time I click on a section of an HTML webpage, JQuery retrieves the ID of that specific tag

How can I retrieve the id of an Html tag that has been clicked by a user on a web page using Jquery? I have attempted to do this, but it seems to only work for specific tags that are passed in the function. $(document).ready(function(){ $("p").click ...

Decreasing the space between columns in Bootstrap 3

My objective is: https://i.sstatic.net/UIPsq.png However, the current layout appears like this (the issue isn't the bottom margins, I've already decided they should be smaller): https://i.sstatic.net/GbLFE.png The problem lies in the gutter s ...

Manage the placement of elements using CSS

Having an issue here. The blue-colored elements are showing up vertically, but I want them to be displayed horizontally. I've tried various methods but haven't been able to solve the problem. Providing just the code for the items below due to len ...

Enhancing CSS to create a more visually appealing loading spinner

I am completely new to CSS and I've been attempting to customize the CSS in the angular-loading-bar module to create a more visually appealing loading spinner. Currently, I have a square spinner that rotates in the center of the page, with a black bor ...

CSS - Issue with aligning image captions

I created an HTML snippet that has the following structure: <div class="large-4 columns"> <div class="promo-box"> <a href="#"> <img src="/our-projec ...

Retrieving data from dynamically generated text inputs using jQuery in ASP.NET MVC forms

Looking for a way to dynamically add text-boxes to my MVC add/edit form. I have a field called 'Interests' where users can add multiple interests by clicking on 'Add another' text box. JQuery can help achieve this functionality. The ...