Copy link to clipboard
Copied
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 a 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?
Copy link to clipboard
Copied
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...
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...
Copy link to clipboard
Copied
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');
Copy link to clipboard
Copied
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 🙂
Copy link to clipboard
Copied
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.
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.
Copy link to clipboard
Copied
EDITED
IF you are using a .php include file then all your other pages will be .php files rather than .html files
By @osgood_
Would it be simpler to use a session variable? Pressing the buttom would set the value of the session to `en` or `es`. The session variable can then be used for the URL.
Copy link to clipboard
Copied
Not really thought about it. 8 lines of javascript is fairly concise. If using a php session variable is simpler then use that workflow.
Copy link to clipboard
Copied
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).
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!
Copy link to clipboard
Copied
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>
Copy link to clipboard
Copied
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.
Copy link to clipboard
Copied
i think you misinterpreted my statement. i am not saying that the flags are not necessary... i am saying that the english flag is not necessary on the english page, only the spanish flag should be present.
likewise on the spanish page the spanish flag is not needed, only the english flag should be present.
if we are on a page written in Spanish, necessarily we see that we are on the Spanish, so the Spanish flag switch is not necessary, especially if we click on it, nothing should happen...
on the other hand, the flag offering me the page in a different language content is totally justified
and if you look at the code I proposed, the one and only button adapts according to the nationality of the page
then, having the English word and/or the English flag, or the Spanish word and/or the Spanish flag, is just a matter of CSS
Copy link to clipboard
Copied
i think you misinterpreted my statement.
No, its something l wondered about when the OP posted saying they had 2 buttons, as flags. Theres really no need to have both, only for visual appeal. I guess it becomes then a matter of personal preference as to whether one thinks including both adds anything to the clarity for the user or visual impact.
Either way both scripts presented can easily be adapted to use 1 button or 1 flag, or both.
Copy link to clipboard
Copied
definitly...I agree
as the OP said that the buttons were in the included header, and it was a two language only, it was easly adaptable to focus on only one swapper button only.
But re reading the OP , I think that the OP was also asking about what mecanism to use for including part of the page ?
Copy link to clipboard
Copied
definitly...I agree
as the OP said that the buttons were in the included header, and it was a two language only, it was easly adaptable to focus on only one swapper button only.
A one flag per page adapted script, assuming flag images are stored in a flags folder. The applicable flag and applicable language link get injected into the <a> tag by the script.
<a href="" class="language"></a>
<script>
const language = document.querySelector('.language');
const url = window.location.href;
const pageName = url.substring(url.lastIndexOf('/')+1);
const currentPage = pageName.split('.');
const currentLanguage = currentPage[0].includes('_es') ? "english_flag.jpg" : "spainish_flag.jpg";
let destinationPage = '';
switch(currentLanguage) {
case "english_flag.jpg":
destinationPage = currentPage[0].replace("_es", "") + ".html"
break;
case "spainish_flag.jpg":
destinationPage = currentPage[0] + "_es.html"
}
language.setAttribute('href', destinationPage);
language.innerHTML = `<img src="flags/${currentLanguage}">`;
</script>
Well plenty to think upon but I think we have it covered from most angles. There should be a solution in this thread which will work for the OPs requirements.
Copy link to clipboard
Copied
Thank you all for your help and sorry I couldn't jump in sooner. I have not been able to try any of the soultions but hope to shortly. Meanwhile, I can join the conversation about button-strategy. This is how I handle it at the moment:
The English page headings show the English flag and the Ecuadorian flag:
The English flag does nothing but has a thick green border to indicate that is the active language. If you click on the Ecuadorian flag it takes you to the Spanish home page (in future it will take you to the parallel Spanish page). Although it's pretty obvious you are on an English page, I think the visual clue is still useful.
On the Spanish pages, the setup is reversed. The Spanish flag is highlighted and clicking on the English flags takes you to the English page.
Showing both flags also shows the user there are 2 choices. I use the Ecuadorian flag because that's where we are. We don't expect many users to recognize it as the Ecuadorian flag but I think it looks "Spanish" enough to serve purpose. I could always put a small "Esp" on it.
Copy link to clipboard
Copied
If that is the concept you require then for the anchor tags use:
<a href="" class="english"><img src="flags/english_flag.jpg" alt="English"></a>
<a href="" class="spanish"><img src="flags/spanish_flag.jpg" alt="Spanish"></a>
Then the below 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", "");
//add border to flag
if(currentPage[0].includes('_es')) {
spanish.style.border = "4px solid green"
}
else {
english.style.border = "4px solid green";
};
english.setAttribute('href', destinationPage + '.html');
spanish.setAttribute('href', destinationPage + '_es.html');
</script>
Copy link to clipboard
Copied
a filter on the active language should be added, just to avoid to reload the same page when the appropriaté language is on.
Copy link to clipboard
Copied
a filter on the active language should be added, just to avoid to reload the same page when the appropriaté language is on.
By @B i r n o u
That should do it:
<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", "");
//add link and border to flag
if(currentPage[0].includes('_es')) {
english.setAttribute('href', destinationPage + '.html');
spanish.setAttribute('href', '#');
spanish.style.border = "4px solid green"
}
else {
spanish.setAttribute('href', destinationPage + '_es.html');
english.setAttribute('href', '#');
english.style.border = "4px solid green";
};
</script>
Copy link to clipboard
Copied
yep, that way, that avoid an unecessary loading...
finally, perhaps that the all script should be placed in an init() function, just in case, the loading of the include HEADER missed some steps...
Copy link to clipboard
Copied
Its a bit over the top, the only thing in the include file would be the 2 simple link tags and the script itself, nothing else can go in it as its a generic file for both languages.
Copy link to clipboard
Copied
you're right, but you know, it's hard to get out of the old habit of asynchronous listeners, and the code that can be reinjected at various times using callback...
Copy link to clipboard
Copied
If the script was being used to interact with any code following it then l would use an onload event listener or you could use window.onload but that is a bit 1990s
Of course today we have defer when an external script is being used at the top of the page.
Yes, l see you are still using var, old habits die hard, nothing wrong with it of course, but times move on.
Copy link to clipboard
Copied
yes I use var when I don't wont to be block scoped. so when first coding (except when I know exactly where I'm going) I use var... and I keep const for real constant that won't never change its value.
So except rarely in the app, where I use const, most of the time I only deal with let and var for scoped value and containing variables that can vary during the process,
i.e in the code that I produce, once I create the second listener, I get out destination and defaultpage_serveur from the init block... so having them as var didn't broke anything...
for sure when the code is validate, definitive and that everyone agree with it, the first one destination will stay var, the second one defaultpage_serveur will become a const, and all the ones that will stay in the init block will became let.
but perhaps that I miss used them, and my process of coding is in a bad way.
Copy link to clipboard
Copied
yes I use var when I don't wont to be block scoped. so when first coding (except when I know exactly where I'm going) I use var... and I keep const for real constant that won't never change its value.
By @B i r n o u
I dont think 'var' is needed any longer, it can be replaced by 'let' in any instance, however I don't really have a problem with anyone using 'var' as its not technically wrong. The introduction of 'let' and 'const' just identified in which scope they could be used a bit clearer for the developer.
I often get annoyed when programs like the 'php storm' editors warning system suggests you might want to use 'let' or 'const' if I do use 'var' - I guess its doing its job in trying to get you to use modern practices but hey I'll decide what I'm going to use, thanks. Until 'var' becomes officially redundant, it isnt, so if its just a coding habit from years of using it, then its really doing no harm.
Im just trying to keep myself evolving, so I rarely use 'var' now.
Copy link to clipboard
Copied
I dont think 'var' is needed any longer, it can be replaced by 'let' in any instance,
By @osgood_
Sorry, I had a conf call...
In fact , var still have the ability to be parsed, where the declaration is made (top, in between function, ... anywhere) before the script execute. you know the two reading passages of the javascript engine...
so var still have the ease of being able to be written in a grouped manner by nature of functionality... while allowing to be used, if necessary, by written blocks upstream.
try
<script>
console.log("'------------------'");
console.log('var : ' + _var_foo);
console.log('let : ' + _let_foo);
console.log('const : ' + _const_foo);
console.log("'------------------'");
var _var_foo = 'ok';
let _let_foo = 'ok';
const _const_foo = 'ok';
</script>
let and const both create a respective error well identified as such, the first let, as a use before declaration, and the second const, as an attempt of second declaration