feat: add automatic HTML lang and dir attributes

- Add updateHtmlAttributes() function to set lang attribute on HTML element
- Automatically add dir=rtl for RTL languages (fa, ar) and remove for LTR
- Initialize attributes on component load with current locale
- Listen for locale changes to update attributes dynamically
- Add rtlLanguages configuration array for maintainability
This commit is contained in:
Goudarz Jafari
2026-02-08 09:56:11 +03:30
parent 4ac141fe36
commit ad48b865f2
+25 -1
View File
@@ -11,6 +11,24 @@ const languages = [
{ code: 'fa', name: 'فارسی', flag: '🦁' }
];
// RTL languages
const rtlLanguages = ['fa']; // ['fa', 'ar']
// Update HTML lang attribute and dir for RTL languages
function updateHtmlAttributes(langCode) {
const htmlElement = document.documentElement;
// Set lang attribute
htmlElement.setAttribute('lang', langCode);
// Set dir attribute for RTL languages
if (rtlLanguages.includes(langCode)) {
htmlElement.setAttribute('dir', 'rtl');
} else {
htmlElement.removeAttribute('dir');
}
}
/**
* Creates and initializes a custom language selector component
* @param {string} containerId - ID of the container element
@@ -32,6 +50,9 @@ function createLanguageSelector(containerId = 'language-selector') {
const currentLocale = window.i18n ? window.i18n.getCurrentLocale() : 'en';
const currentLang = languages.find(l => l.code === currentLocale) || languages[0];
// Set initial HTML attributes
updateHtmlAttributes(currentLocale);
// Create toggle button
const toggle = document.createElement('div');
toggle.className = 'language-selector-toggle';
@@ -150,6 +171,9 @@ async function selectLanguage(langCode, container) {
await window.i18n.setLocale(langCode);
}
// Update HTML lang attribute and dir for RTL languages
updateHtmlAttributes(langCode);
updateSelectedLanguage(langCode, container);
closeDropdown(container);
}
@@ -178,4 +202,4 @@ function updateSelectedLanguage(langCode, container) {
// Create language selector when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
createLanguageSelector();
});
});