Search code examples
javascriptcssvue.jsvuejs2right-to-left

Change direction with selecting Language in Vuejs


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?


Solution

  • 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')
      }
    }