3

I have a Language select-option. If I choose Arabic then it will change the direction.

* {
  direction: rtl!important;
}

While I am using this, then the whole direction changed to right to left. But how can I do that with Methods?

methods: {
  languageSelection() {
     if(this.lang == 'arb') {
        document.getElementsByTagName("*")[0].style.direction = "rtl!important";
        document.getElementsByTagName("html")[0].style.direction = "rtl!important";
        document.getElementsByTagName("body")[0].style.direction = "rtl!important";
      }
   }
}

The above code is not working! If I can add a CSS file then it will be better for me. For example:

languageSelection() {
  if(this.lang == 'arb') {
     // active a css file like: style-rtl.css
  }
}

But how is this possible?

3 Answers 3

1

Ok. So when you use getElementsByTagName("*")[0] you will probably get a handle to a <html> element. So the same element you're accessing in the next line.

To change all elements direction you would have to iterate over the collection:

const elems = document.getElementsByTagName("*")
for (let elem of elems) {
    elem.style.direction = 'rtl'
}

But this will still include <script>, <style>, <meta> tags, which is not the best solution.

My solution

I would create class in the css

html.is-rtl * {
    direction: rtl;
}

then just toggle the class when you select the language which is read from right to left.

languageSelection() {
  if (this.lang == 'arb') {
     document.querySelector('html').classList.add('is-rtl')
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Could create a stylesheet and append it to the head:

languageSelection() {
  if(this.lang == 'arb') {
     const style = document.createElement('style');
     style.innerHTML = `*{direction:rtl!important}`;
     document.head.appendChild(style);
  }
}

2 Comments

Will it create every time of language changing or one time?
It the function runs every time the select is changed then yes. You'd have to add an ID and check it doesn't exist first
0

You should manage it inside App.vue. add custom css class based on chosen language to #App element.

<template>
  <div id="app" :class="{'dir-rtl': isRtl}">
    ...
  </div>
</template>
<script>
export default {
  computed: {
    isRtl () {
      return this.lang === 'arb'
    }
  }
}
</script>
<style lang="scss">
.dir-rtl {
  direction: rtl !important;
}
</style>

best place to save and change lang is vuex store.

1 Comment

I am storing the language variable in localStorage. I thought about vuex but I think it's better to use localStorage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.