farbon Larseige
farbon Larseige

Reputation: 41

JavaScript to flip texts horizontally

I want to change direction of web page, I could change it using CSS method like below:

.flip {
-moz-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
-o-transform: scaleX(-1);
transform: scaleX(-1);
-ms-filter: fliph; /*IE*/
filter: fliph; /*IE*/
}

and add class flip into body section like this:

    <body class="flip">

As you know, page will flip horizontally completely, the problem is texts in page, that we can't read it, I'm looking for a solution to use JavaScript to UN-FLIP ONLY TEXTS in page. I mean only texts will be back to normal.

Is there anyway to use JavaScript to un-flip only texts in page?

I highly appreciate your help on this issue.

Thanks in advance

Upvotes: 1

Views: 521

Answers (3)

Abhishek
Abhishek

Reputation: 151

To flip text Horizontally only with pure Javascript, we can achieve it with some combination of some Methods and Regex.

text = text.split('').reverse().join('');

Here is an Example

function fliptext(word){
    var text = word
    text = text.replace(/\r/gi,'');
    text = text.replace(/([^a-z 0-9\n])/gi,' $1 ');
    text = text.split('\n').reverse().join('\n');
    text = text.split('').reverse().join('');
    text = text.replace(/ ([^a-z 0-9\n]) /gi,'$1');
    return text;
}

console.log(fliptext("Nice Game")); // emaG eciN

Upvotes: 1

Eran Shabi
Eran Shabi

Reputation: 14999

First you need some class which make elements flip:

.flip {
    transform: scaleX(-1);
}

Then let's add this class to each element with no children (That's a simple way to find elements with only text):

Array.prototype.slice.call(document.querySelectorAll("body *"))
    .filter(ele => ele.children.length === 0)
    .forEach(e => e.className += " flip");

And now we only need to add this class to the body and that's it:

document.body.className += " flip";

Please note that this way does not flip text nodes, as they are not elements and can't have class. If you have text nodes my advice is to wrap them in <span>. See answer for how to get text nodes.

So a js-only solution would be:

document.head.innerHTML += "<style>.flip{transform: scaleX(-1);}</style>";

Array.prototype.slice.call(document.querySelectorAll("body *"))
    .filter(ele => ele.children.length === 0)
    .forEach(e => e.className += " flip");

document.body.className += " flip";

Upvotes: 0

Roger Ng
Roger Ng

Reputation: 779

You can simply use CSS to unflip the flipped text.

.flip {
  -moz-transform: scaleX(-1);
  -webkit-transform: scaleX(-1);
  -o-transform: scaleX(-1);
  transform: scaleX(-1);
  -ms-filter: fliph;
  /*IE*/
  filter: fliph;
  /*IE*/
  border: 3px dashed red;
}
.flip>p {
  -webkit-transform: scaleX(-1);
  -o-transform: scaleX(-1);
  transform: scaleX(-1);
  -ms-filter: fliph;
  /*IE*/
  filter: fliph;
}
<main class="flip">
  <p>FLIPPING? NO!</p>
</main>

Upvotes: 2

Related Questions