John
John

Reputation: 707

How to set proper element css direction (ltr / rtl) according to it's inner text (english / arabic)?

I want to make right to left alignment of text for Arabic language & reverse for English on Button click. I can do this by changing every text alignment dynamically for English & Arabic that's lengthy process.

So can any body gives an idea for doing in short. Any suggestion really appreciate.

Upvotes: 3

Views: 5635

Answers (3)

Arash Yazdani
Arash Yazdani

Reputation: 302

I used this solution

Add this class in CSS

.rtl{direction:rtl;text-align:right;}

then use this code in any items you want to be right to left

<div class="@(Model.RtlEnabled ? "rtl" : "")"> Your right to left text <div>

I use this in ASP.Net core you can change it for your code.

Upvotes: 1

geevee
geevee

Reputation: 5451

you can set content direction easily with css.

html:

<div class="rtl">اليمين إلى اليسار</div>
<div class="ltr">Left to right</div>

css:

.rtl{direction:rtl;text-align:right;}
.ltr{direction:ltr;text-align:left;}

EDIT:

to make this dynamically happen on button click, do as following:

javascript & jQuery (i suggest using jQuery in that case):

// function that returns true if input is arabic, else false
function is_arabic(str) {
    var arabic = /[\u0600-\u06FF]/;
    return arabic.test(str);
}

// on button click
$(function(){
    $('#buttonID').click(function(){ // assuming 'buttonID' is the button id
        $('div').each(function(){ // iterate all DIV elements 
            if (is_arabic($(this).text())
                $(this).addClass('rtl').removeClass('ltr');
            else
                $(this).removeClass('rtl').addClass('ltr');
        });
    });
});

just make sure to use the CSS rules a mentioned above.

hope that helps.

Upvotes: 8

Ghyath Serhal
Ghyath Serhal

Reputation: 7632

Add a dir attribute on your body or div as shown below

<div dir="rtl"></div>

Upvotes: 3

Related Questions