cleanwater
cleanwater

Reputation: 53

Put the text right-aligned

I'm working with codepen.io and I am creating a bargraph. The graph has scales: One on the left and one on the right side.

The problem is that I want the text of value on the left side to be right-aligned. I can't use CSS to do this, and I believe javascript would do the job.

Here are the two functions I am using to draw the scales and the link to my project goes bellow.

function drawScalesLeft(numOfScales)
{
    console.log("Zeichne linke Skala mit " + numOfScales + " Einheiten");
    for(i=0; i <= numOfScales ; i++)
    {
        var currentHeight = document.getElementById('bargraph').height;
        var yPos = 279.75 * i / numOfScales + 10;
        var marker = document.createElementNS(svgNS,"rect");
            marker.setAttributeNS(null, 'x', 115);
            marker.setAttributeNS(null, 'y', yPos);
            marker.setAttributeNS(null, 'height', 0.2);
            marker.setAttributeNS(null, 'width', 10);
        document.getElementById("bargraph").appendChild(marker);
        var markerText = document.createElementNS(svgNS,"text");
            markerText.setAttributeNS(null, 'x', 50); //Textposition (horinzontal)
            markerText.setAttributeNS(null, 'y', yPos+5);

            markerText.textContent = (100-100 *i/ numOfScales).toFixed(digits) + " %";
        document.getElementById("bargraph").appendChild(markerText); 
   }
}

function drawScalesRight(numOfScales)
{
    console.log("Zeichne rechte Skala mit " + numOfScales + " Einheiten");

    for(i=0; i <= numOfScales; i++)
    {
        var currentHeight = document.getElementById('bargraph').height;
        var yPos = 279.75 * i / numOfScales + 10;
        var marker = document.createElementNS(svgNS,"rect");
            marker.setAttributeNS(null, 'x', 175);
            marker.setAttributeNS(null, 'y', yPos);
            marker.setAttributeNS(null, 'height', 0.2);
            marker.setAttributeNS(null, 'width', 10);
        document.getElementById("bargraph").appendChild(marker);
        var markerText = document.createElementNS(svgNS,"text");
            markerText.setAttributeNS(null, 'x', 195);//Textposition (horinzontal)
            markerText.setAttributeNS(null, 'y', yPos+5);
            markerText.textContent = (500-500 * i/ numOfScales).toFixed(digits2) + " m";
        document.getElementById("bargraph").appendChild(markerText);
    }
}

Full code:

codepen.io/Cleanwater/pen/LWQyJm?editors=0010

Upvotes: 0

Views: 54

Answers (1)

m1kael
m1kael

Reputation: 2851

You need to properly calculate the x value for the text nodes.

After line 55 that looks like this

document.getElementById("bargraph").appendChild(markerText); 

add this

markerText.setAttributeNS(null, 'x', 100 - markerText.getBBox().width);

And all should be good.

Also, remove line 50

markerText.setAttributeNS(null, 'x', 50); //Textposition (horinzontal)

Upvotes: 1

Related Questions