-1

I am using a language switcher to change language, with this code I am able to change language via jQuery

Code in index.php

< link class="css_en" rel="stylesheet" href="css/index-en.css" >

Code in LanguageSwitch.js

    this._langSwitchUI.find('.primary-lang').click(function(event){
        event.preventDefault();
        StorageUtil.setLanguage(Languages.PRIMARY);
        _this._closeSelect();
        if (jQuery('.css_en').length) {
            jQuery('.css_en').remove();
            jquery('<link class="css_ar" rel="stylesheet" href="css/index-rtl.css">').appendTo('head');
        }
    })
    this._langSwitchUI.find('.secondary-lang').click(function(event){
        event.preventDefault();
        StorageUtil.setLanguage(Languages.SECONDARY);
        _this._closeSelect();
        if (jQuery('.css_ar').length) {
            jQuery('.css_ar').remove();
            jquery('<link class="css_en" rel="stylesheet" href="css/index-en.css">').appendTo('head');
        }
    })
  • 1
    Assuming that you want to dynamically add the stylesheet, then you need to actuall add it to the DOM. Put `.appendTo('head')` at the end of tje jQuery object containing the `` element. ***However*** note that the far better way to do what you need is to have the ltr and rtl styling *always* included in your CSS (which should be minified and cached) and then switch between the necessary text direction using a class on the `body` which should be used as the base selector for each rtl/ltr setting. – Rory McCrossan Aug 15 '22 at 16:01

1 Answers1

1

You need to use jQuery('head').append(...)

this._langSwitchUI.find('.primary-lang').click(function(event){
    event.preventDefault();
    StorageUtil.setLanguage(Languages.PRIMARY);
    _this._closeSelect();
    if (jQuery('.css_en').length) {
        jQuery('.css_en').remove();

        jQuery('head').append('<link class="css_ar" rel="stylesheet" href="https://mywebsite.com/css/index-rtl.css">');
    }
})

this._langSwitchUI.find('.secondary-lang').click(function(event){
    event.preventDefault();
    StorageUtil.setLanguage(Languages.SECONDARY);
    _this._closeSelect();
    if (jQuery('.css_ar').length) {
        jQuery('.css_ar').remove();

        jQuery('head').append('<link class="css_en" rel="stylesheet" href="https://mywebsite.com/css/index.css">');
    }
})
Richard Dobroň
  • 687
  • 4
  • 6