Skip to main content
Galeodan
Known Participant
May 16, 2021
Question

How do I configure "smart" language-switch buttons in an included HTML header?

  • May 16, 2021
  • 5 replies
  • 5852 views

Nutshell: Does a button in an included header know what page it is on?

 

Background: I am in the process of completely re-coding some bilingual websites that were generated using Netobjects Fusion. Each site has a homepage and complete web structure in English and a parallel structure in Spanish. So I have a page: aboutus.html and aboutus-es.html & so on. The Spanish page (home-es) is below the English home page (index.html. Every page has 2 language switch buttons in the header: English and Spanish actually as flags. The buttons take you to the respective home page - Not best for the user but it was easier for me :).  (Using Google-Spanish or equivalent is not an acceptable solution for us.) The sites need to be completely rebuilt but I am satisfied with the basic structure and plan to retain that for the time being. All of this was easy in Fusion and I am trying to save myself a lot of work and pain by having included headers, footers, menus etc. in the pages that I will code in HTML. While open to other suggestions, my reading so far indicates that using server-side includes with w3-include-html attribute or PHP would be the most practical solution, assuming my host allows it (am asking).  

 

Questions: I want the language buttons, which are in the included headers, to take the user to the equivalent page in the other language rather than always to the home page. I am hoping that I can use some simple JS to have the button go look on the page it finds itself in for the correct link. That means the buttons will have to "know" what page they are on. Is all of this feasible? Does it depend on how I include the headers? Is there a better way to include the headers with this functionality in mind?

    This topic has been closed for replies.

    5 replies

    Liam Dilley
    Inspiring
    May 18, 2021

    Is this site just all manual and no CMS / Headless CMS driven at all?

    B i r n o u
    Legend
    May 19, 2021

    three that everyone has a song and dance... and the OP still hasn't intervened in the debate...

    Galeodan
    GaleodanAuthor
    Known Participant
    May 19, 2021
    quote

    three that everyone has a song and dance... and the OP still hasn't intervened in the debate...


    By @B i r n o u

     

    Hi everyone - I would love to intervene in some constructive way but, as I mentioned before, I lost my computer and an awaiting a replacement which I am hoping arrives today, via Amazon and a visiting friend from the USA. So I have not been able to try any of the suggestions yet. But the following may help:

     

    Spanish headers only go on Spanish pages: English on English. So I anticipated that the JS in the included header to activate a link on the "host" page should be very simple (maybe 1 line?). Similarly the JS on the "host" page would be just as simple, calling the equivalent page in the other language. I would try it if I could but that will have to wait.

     

    Thinking further: I will probably dispense with one of the buttons. So if you are on the English page you see the Spanish flag button and vice-versa. 

     

    Of course, I still have to choose a mechanism to do the actual inclusion. I was thinking PHP, in which case all my pages would have to be .php's - Is there any downside to this? How about the w3-include-html attribute?

     

    Regarding the cookie debate: maybe when the user clicks to change language a popup simply asks:

    "Would you like us to save this choice for future visits (using a cookie)?"

     

     

     

    B i r n o u
    Legend
    May 17, 2021

    from my point of view, I would say that the 'English' toggle button is not useful on the English page, and similarly the 'Spanish' button is not necessary on the Spanish page.


    Therefore, and since you only have two languages available, only one button can be used.


    so if in your page that is going to be included (the header page) you add on one hand the tag representing the button, and on the other hand the Javascript ... that should do the job.


    (no need to add the script independently, as the header is common to each page, so you might as well avoid a request)

    so the code to add to your header would look like this

     

    <button id="swap_btn"></button>
    <script>
    
        var destination = '';
        var defaultpage_serveur = 'index'
        window.onload = init()
    
        function init() {
            var page_location = window.location.href;
            var page_filename = page_location.substring(page_location.lastIndexOf('/') + 1);
            var page = page_filename.split('.')[0].split('-');
            var language = '';
            if (page[1] != 'es') {
                destination = ((page[0] == '') ? defaultpage_serveur : page[0]) + '-es.html';
                language = "Spanish"
            } else {
                destination = page[0] + '.html'
                language = "Original"
            }
            var swap_btn = document.getElementById('swap_btn');
            swap_btn.onclick = swap_btn_action
            swap_btn.innerText = language
        }
    
        function swap_btn_action() {
            window.location.href = destination
        }
    
    
    </script>

     

    Legend
    May 17, 2021
    quote

    from my point of view, I would say that the 'English' toggle button is not useful on the English page, and similarly the 'Spanish' button is not necessary on the Spanish page

     

    By @B i r n o u

     

    I think it can be useful in terms of visual appeal if flags are used, although its not strictly necessary. My issue with using a button is that it looks a bit dull, whereas using images of country flags is visually more pleasing........you could always swap the flags according to which language page you are on if you didnt want both the English and Spanish flags on the page at the same time.

    B i r n o u
    Legend
    May 18, 2021

    I would argue that is down to wayward coding management, trying to output something that hasnt been declared.........hummm. l guess lm a bit more organised as l would not really attempt to do that.


    Let me try to contextualize this approach. In fact it is very very usefull... (remember that I have adopted an agile methodology for a long time ago)...

     

    good practice for declaring variables is that all var's are declared at the top of the file. so far... why not...

     

    however, let's imagine an application context during development, and so we have a whole block composed of several functions specific to data management. preceded by the declarations of the variables specific to this whole mechanism... so far so good...


    now, let say that we want to provide the system with a particular functionality specific to the smoothing / formatting of data ... so we will be towards the bottom of the file to add new functions... and on this occasion, we may have to deploy a panoply of variable ... for my part, I declare them just before these functions in the lower part of the file ... in order to have them on hand and especially to act (modification, deletion, grouping object, transtyping ... etc ...) according to the advancement of needs and development ...

     

    as soon as we need an injection in one of the previous functions specific to data management (the upper blocks)... we just have to add a /* TODO VARIABLE _var_name USAGE NOT CONFIRMED */ preceding the injection of this variable in the concerned blocks... and hop, the Javascript engine won't complain... (because of the two reading passage of Javascript, using variable in the code before declaring it) and so we can preserve our comfort and flexibility of writing and injection... free to us to remove anything whgen code is over... and if the var doesn't go to the top...

     

    an other approach will be to have a separate file added... sometimes I also use this technic, but that will require a second declaration in the first file.

     

    Object VAR are often quite good for such elasticity... but those two last comments are not the subject... the subject was why using var before declaring them...

     

    Nancy OShea
    Community Expert
    Community Expert
    May 16, 2021
    quote

    Nutshell: Does a button in an included header know what page it is on?

     

    Background: I am in the process of completely re-coding some bilingual websites that were generated using Netobjects Fusion.

    ===========

    Short Answer: No.  HTML alone doesn't DO much of anything except provide structure for content. 

     

    NetObject Fusion:  Ugh! You have my deepest sympathies.  Throw everything out and use WordPress with the WP Multi-Lingual Plugin (WPML).

    https://wpml.org/

     

    I beta tested and wrote tutorials for NOF users so I say this with more than casual experience using it.  What NOF did to botch up code was unforgivable but understandable given that it was never a code editor.  It was a Code Generator supported in large part by optional add-ons or 3rd party widgets  -- the same ilk as GoLive and Muse, all of which are dead now.  Nothing generated by NOF is worth salvaging except the basic, unstyled text content which you should strip and paste into WordPress.

     

    Good luck with your project!

     

    Nancy O'Shea— Product User & Community Expert
    Legend
    May 16, 2021

    An alternative but much the same:

     

    2 anchor tags for the English & Spanish flag icons:

     

    <a href="" class="english">English Flag</a>
    <a href="" class="spanish">Spanish Flag</a>

     

    Assuming your page naming convention is:

    aboutus.html (English)

    aboutus_es.html (Spanish)

    contact.html (English)

    contact_es.html (Spanish)

     

     

    The javascript -

     

    <script>
    // assign language anchor tags to variables
    const english = document.querySelector('.english');
    const spanish = document.querySelector('.spanish');
    // get current url
    const url = window.location.href;
    //get pageName from url string
    const pageName = url.substring(url.lastIndexOf('/')+1);
    // remove .html from page name
    const currentPage = pageName.split('.');
    // remove _es from page name
    const destinationPage = currentPage[0].replace("_es", "");

    english.setAttribute('href', destinationPage + '.html');
    spanish.setAttribute('href', destinationPage + '_es.html');

    </script>

     

     

    EDITED

    IF you are using a .php include file then all your other pages will be .php files rather than .html files

     

    IF that is the case then change the .html in the last 2 lines of the javascript block of code to .php as below:

     

    english.setAttribute('href', destinationPage + '.php');
    spanish.setAttribute('href', destinationPage + '_es.php');

    Galeodan
    GaleodanAuthor
    Known Participant
    May 16, 2021

    Birnou & Osgood: thank you both for your suggestions. I have almost zero knowledge of JS, so I do need simple. And I won't be able to test either solution for a few days when I get a replacement computer (if it arrives). In both cases, do I understand correctly thet the script is on the English or Spanish page rather than in the "included" header? If so, that would indicate the the header can call a function on the page into which it has been included - It knows where it is, so to speak. So the button in the header could have JS to find a specific ID on the page it finds itself on. At that ID, I would have a simple link: On the English page, "aboutus.html", this link would point to "aboutus-es.html". And on the Spanish page, "aboutus-es.html", the link would point to "aboutus.html". These links would be invisible to the user and execute automatically. I would have to code specific links for every page, but that would not be a burden - The rest of the page is different in any event. Perhaps I have this all wrong - I would NOT be surprised 🙂

    Legend
    May 16, 2021
    quote

    Birnou & Osgood: thank you both for your suggestions. I have almost zero knowledge of JS, so I do need simple. And I won't be able to test either solution for a few days when I get a replacement computer (if it arrives). In both cases, do I understand correctly thet the script is on the English or Spanish page rather than in the "included" header? 🙂


    By @Galeodan

     

    The script can be inserted in the 'included' header file, otherwise you would have to include the script in each individual page, which defeats the object because if you want to change the script at any time in the future you would have to update all the pages where the script resides rather than in just the 1 file.

     

    quote

     It knows where it is, so to speak. So the button in the header could have JS to find a specific ID on the page it finds itself on. At that ID, I would have a simple link: On the English page, "aboutus.html", this link would point to "aboutus-es.html". And on the Spanish page, "aboutus-es.html", the link would point to "aboutus.html". These links would be invisible to the user and execute automatically. I would have to code specific links for every page, but that would not be a burden - The rest of the page is different in any event. Perhaps I have this all wrong - I would NOT be surprised 🙂


    By @Galeodan

     

    Yes, the links would be invisible to the user, they would either click a button or a flag option, depending on which script you use, which takes them to the correct language page.

     

     

     

     

    B i r n o u
    Legend
    May 16, 2021

    well without seeing your tree and the full web site structure, it's complex to help you in a precise way.

    also, without knowing your javascript knowledge, it's not easy too to approach a modern structure of code... (if you want to learn, I keep it basic)...

     

    so to keep it basic, I will say to rename too your spanish home page, from (home-es.html to index-es.html)

     

    then as I don't know if you use or not PHP, I dind't use any PHP and stuck with vanilla JavaScript... that will drive to a complex deal with the URL location... butr we will see it in detail, step by step, just below...

     

    let say that you have in each page a HTML button for swapping language... no label, just and ID, I will let you add the appropriate CSS

    <button id="swap_btn"></button>

     

    now you can add to each page of your web site, a Javascript that will handle the init process, and the action process

     

    so first we need two variables accessibles from all outside function, and from everywhere in the page...

    1. destination for handling the page destination
    2. and defaultpage_serveur for the page root name (in our case as I said above 'index')

     

    so add them to the Javascript file

    var destination = '';
    var defaultpage_serveur = 'index'
    

     

    now the init function will execute when the page will load

    first we get the url location of this page and extract the filename i.e something.html or something-es.html

    it's important to understand that if the URL point to the folder root... the system wont return index.html but an empty string... so it's important for the init function tu anticpate this behavior... we will see it later on

     

    we then remove the .html extension and get the nude page name ... i.e something, or something-es

    we could then extract the root of the page (I mean without the probable -es in case it exists...) i.e something in both case

     

    and if we don't find it (I mean an empty string)... that mean that we are on a native page...

     

    in that case, we have to check if the -es is not found... and so check if we are on a page URL or a folder root URL

     

    we then add the -es.html to the end of the appropriate destination

    we also set the listener to the button (action)

    and finally we can also set the appropriate button label using the innerText property

     

    now we can read the code

     

    function init(){
        var page_location = window.location.href;
        var page_filename = page_location.substring(page_location.lastIndexOf('/')+1);
        var page = page_filename.split('.');
        var pageroot = page[0].split('-');
        var language = '';
        if (pageroot[1] != 'es') {
            if (pageroot[0] == '') {
                destination = defaultpage_serveur + '-es.html'
            } else {
                destination = pageroot[0] + '-es.html'
            }
            language = "Spanish"
        } else {
            destination = pageroot[0] + '.html'
            language = "Original"
        }
        var swap_btn_btn = document.getElementById('swap_btn');
        swap_btn_btn.onclick = swap_btn_action
        swap_btn_btn.innerText = language
    }

     

    now it's time to add the callback added to the button listener

     

    function swap_btn_action(){
        window.location.href = destination
    }

     

    now load everything and give it a test... if you need any further help please, don't hesitate...

    but as I said, it's not a compact modern JavaScript, but I think that it is most clear, and easy to understand the logic behind...