/javascript-language-switcher

Simple JavaScript Language Switcher, use javascript switch language with a help of the css display.

Primary LanguageHTMLGNU General Public License v3.0GPL-3.0

Javascript Language Switcher

after quite a bit of searching, I decided to create a naive one

you can just fork it to use it

simple demo

jQuery Hide & Show

At the first I thought I can use jQuery's .hide() and .show() to achieve the result I want.

First Naive Version

HTML

    <h1 class="en">JavaScript Language Switcher</h1>
    <h1 class="tw">JS語言切換</h1>
    <span class='en' onclick="switch_lang('.en', '.tw')">中文</span><span class='tw' onclick="switch_lang('.tw', '.en')">EN</span>

JS

window.onload = switch_lang('.tw', '.en');

function switch_lang(hide_lan, show_lan){
  $(hide_lan).hide();
  $(show_lan).show();
}

Then I quickly found that the user with javascript disabled or slow load in would result in seeing the original HTML w/ multiple langs not being hidden.

So I've tried to initialize the hidden lang by set CSS visible to hidden.

CSS Visibility

.tw {visibility: hidden;}
.en {visibility: visible;}

But it resulted in a disordered layout.(You can regard it as what when we set the colour: white; to cover something up)
Finally with the help of another style attribution, display, I am able to achieve what I want - to set up a multilingual site and handle the error when users have a low load-in speed or JS disabled.

CSS Display

.tw {display: none;}

Result: Simple JavaScript Language Switcher w/ css display (chienhsiang-hung.github.io)

How to use it

The example was shown for TW-EN site.

Set up your HTML like this:

<h1  class="mt-5 en">Simple JavaScript Language Switcher w/ css display</h1>
<h1  class="mt-5 tw">藉由CSS實現簡易JS語言切換</h1>
<span  class='en'  onclick="switch_lang('.en', '.tw')">中文</span><span  class='tw'  onclick="switch_lang('.tw', '.en')">EN</span>

Put this in <head> part of your HTML:

<link href="https://chienhsiang-hung.github.io/javascript-language-switcher/src/css/switch-lang-display.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

And this in <body> part of you HTML:

<script src='https://chienhsiang-hung.github.io/javascript-language-switcher/src/js/switch-lang-no-onload.js'></script>

Support

It's always appreciated if you would like to buy me a cofee to support this API. Thank you :)