Search code examples
angularjssvgcoffeescriptsasstooltip

How can I make the width of my div expand with it's content within a tooltip?


I have functioning tooltip that I would like to make responsive based on it's content. According to the inspector it is inheriting a width of 75px (I do not know from where) and then all the content is wrapping to the next line. I noticed if I change the positioning to relative all the text will go on one line, however I need to keep it's positioning absolute in order to make it appear above the svg. How can I achieve this?

I've already tried "display: inline-block" and using"float". Neither works.

<div class="tooltip-wrapper">
   <div class='tooltip'>
        {{content}}
    </div>

    <svg>
        <use xlink:href={{icon}}>
    </svg>
</div>

.tooltip-wrapper {
    position: relative;
    cursor: pointer;

    svg {
        height: 0.75rem;
        width: 0.75rem;
    }

    &:hover {
        .tooltip {
            opacity: 1;
        }
    }
}

.tooltip {
    position: absolute;
    bottom: calc(100% + 1rem);
    background-color: rgba($black, 0.7);
    border-radius: 2px;
    color: $white;
    padding: 0.5rem;
    opacity: 0;
    transition: opacity $transition-timing ease;

    &:before {
        content: '';
        position: absolute;
        bottom: -0.3rem;
        left: 50%;
        margin-left: -0.3rem;
        @include triangle(0.7rem, rgba($black, 0.7), down);
    }
}

controller: ($element, $scope) ->
    $scope.content = "Content stuff and stuff"
    $scope.icon = "#icon-history"

link: (scope, element, attrs, ctrl) ->
    @tooltipWrapper = element[0].children[0]
    @tooltipIcon = @tooltipWrapper.children[1]
    @tooltipContent = @tooltipWrapper.children[0]

    console.log @tooltipWrapper

    element.on 'mouseenter', =>
        @_dropdown()

    @_dropdown = (offset) =>
        Lcontent = @tooltipContent.innerHTML
        Lsplit = Lcontent.split(' ')
        leng = 0

        for i of Lsplit
            leng += Lsplit[i].length
        # console.log leng

        if leng > 10
            $(tooltipContent).css('width', @tooltipContent.width)
        console.log @tooltipContent.width //this returns undefined

        @left = -(@tooltipContent.offsetWidth - @tooltipIcon.offsetWidth) / 2
        $(tooltipContent).css('left', @left)

Solution

  • This is what I was missing.

    'white-space: nowrap;' inside of my 'tooltip' class. I then added the code below inside of my '@_dropdown function so it would eventually go on multiple lines if I had tons of content.

    if leng > 50
        $(tooltipContent).css({"width": '360px', 'white-space': 'initial'})