Changing the selected Menu items class across pages - javascript

For my website project I am using ASP.NET MVC "Razor". Learning as I go.
I have 5 or 6 pages on my site, and one page that is on another site. I want users to feel like they are using the same site for all.
There is a typical HTML menu for the pages which follows the standard pattern of using a XHTML unordered list and CSS to layout:
<ul id="menu">
<li class="selected">Home</li>
<li>cek.log</li>
<li>Services</li>
<li>Charlie's Stuff</li>
<li>Contact</li>
</ul>
Elsewhere on SO I found questions similar to mine, where people wanted to track the selected menu item, but within a dynamic page. For example:
Javascript Changing the selected Menu items class
But this approach won't work in my case because in my case the user is not changing a selection on one page, but navigating to another page completely.
How can this be done?

...and I figured it out.
I used Razor to implement this on the server side.
First I implemented a function on my _SiteLayout.cshtml page (the template all pages use):
#functions {
public string Selected(string PageTitle) {
if (Page.Title == PageTitle)
return "selected";
else
return "";
}
}
Then I used this function in my list:
<ul id="menu">
<li class="#Selected("Home")">Home</li>
<li class="#Selected("cek.log")">cek.log</li>
<li class="#Selected("Services")">Services</li>
<li class="#Selected("Charlie's Stuff")">Charlie's Stuff</li>
<li class="#Selected("Contact")">Contact</li>
</ul>
Works perfectly. On my external page, I just hand-coded it since it's based on Wordpress and not Razor.

Related

Targeting a html element but only on specified page

I'm using a shop CMS that allows me to apply a side menu for all product categories, let's call them Necklaces and Rings, that CMS also has an option to add "New" and "Promotions" to that side menu globally, however what I cannot do is specify where I want these "New" and "promotions" to be. For example I want them to be displayed in Rings category but not in Necklaces.
This is a rough sketch how the website is made:
<div class="menu" id="side_menu">
<ul class="standard">
<li id="category_newstuff">New</li>
<li id="category_14">Collection1
<li id="category_14">Collection2
<li id="category_14">Collection3
<li id="category_14">Collection4
<li id="category_promotions">Promotions</li>
</div>
What I want to achieve:
If the page is: rings.html then find "li id="category_newstuff" and apply "style="display"none">
I'm sorry if this is all gibberish lol.
Just add a class on your body tag. For example, the page you want to apply the style to, will have <body class="with-style"> and in the css file, you can simply write .with-style .category_newstuff { display: none; }, or just find .with-style .category_newstuff via JS and hide it.

Jquery ajax clear before reload

I know this is a topic discussed here many times, but none of the solution of the site have helped me....
I'm having two nav items and both of them load two different PHP files by using jquery ajax. I'm using jquery mobile.
My problem is that whenever i click on the other nav item the other one doesn't clear itself, so basically i get div on top of div.
I've tried .html(""); but hasn't worked for me so far.
HTML:
<div id="tabs">
<ul>
<li><a class="classloader1">Upcoming</a></li>
<li><a class="classloader2">History</a></li>
</ul>
</div>
<div id="content"></div>
JS:
$(".classloader1").click(function(){
$("#content").load("get.php");
})
$(".classloader2").click(function(){
$("#content").load("history.php");
})
I would try a different tab structure like
<div id="tabs">
<ul>
<li><a class="classloader one">Upcoming</a></li>
<li><a class="classloader two">History</a></li>
</ul>
</div>
where both elements share the classloader class name. Then I would use jQuery .html() to load the content but returning the specific file depending on the clicked tab like :
$(".classloader").on("click", function (event) {
var file = $(event.target).hasClass("one") ? "get.php" : "history.php";
$("#content").html(function () {
return $(this).load(file);
});
});
If you have more than two tabs, you could use a switch statement to set the value of the file var.
See DEMO
UPDATE : see DEMO using jQuery mobile.

Static Html Website - Bootstrap - Multi language Support

To begin with I want to state that I am newbie in Web Development.
I was asked to build a static website (for a small - size hotel), and I bought this responsive html5 - CSS3 template. It consists of pure html5 - css3 , and some JavaScript for slideshows etc and uses the bootstrap framework.
I have already build the website, and now I was asked to add multilanguage support to it. Can I accomplish this via bootstrap? Can it even be done with CSS?
If not, should I have a copy of all my .html files in a subfolder (e.g "website"/en/"content" ) and redirect the user via a link at the top of the page, or should I use JavaScript to decide the language?
Briefly, I would like a user that visits my website from another country to get the English version of the site, while all others get the default language. I want as fast development as possible (that's why I bought a template) to get up and running asap (summer season has already started). I have a reasonable background in programming, but I am totally new in Web Development.
You can do this within a single file without using any server-side programming languages. You should check out i18next for a proper javascript solution.
You can also use pure CSS to translate a homepage. Try something like
.en, .de, .it { display:none; } /* hide all elements with a language class */
.en:lang(en), .de:lang(de), .it:lang(it) { display:block; } /* show those elements that match their language class */
When you set a proper lang attribute on your html tag (e.g. by javascript) you can translate your page very easy:
<div class="en">Good morning</div>
<div class="de">Guten Morgen</div>
<div class="it">Ciao</div>
Bootstrap has nothing to do with that. No, you cannot translate a site using pure CSS. You'll have to change the HTML source to contain different text. Yes, you can do that by making a copy of all your HTML files and changing the text in them. Typically you'd have a server-side language with HTML templates which enable you to swap in translations for text dynamically without having to have a complete copy of your code. However, it doesn't sound like this is something you would be able to get up and running quickly enough.
Detection of client language and serving an appropriate version of the site is also something that will require some amount of server-side programming. Again, it doesn't sound like something you would be able to get into quickly enough.
Another example of the same thing what guys are already saying
let langs = ['en', 'fr', 'it'];
let lang = 'en';
setLangStyles(lang);
function setStyles(styles) {
var elementId = '__lang_styles';
var element = document.getElementById(elementId);
if (element) {
element.remove();
}
let style = document.createElement('style');
style.id = elementId;
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = styles;
} else {
style.appendChild(document.createTextNode(styles));
}
document.getElementsByTagName('head')[0].appendChild(style);
}
function setLang(lang) {
setLangStyles(lang);
}
function setLangStyles(lang) {
let styles = langs
.filter(function (l) {
return l != lang;
})
.map(function (l) {
return ':lang('+ l +') { display: none; }';
})
.join(' ');
setStyles(styles);
}
Italiano
English
French
<p lang='it'>Ciao a tutti!</p>
<p lang='en'>Hi everyone!</p>
<p lang='fr'>Bon Baguette!</p>
If your website it supposed to be static and use the same solution as the bootstrap page, that is powered by Jekyll, you can use Jekyll and github pages to mark in the template text files and reference externally in a Yaml file that holds the strings in each language (like en.yml and br.yml).
So when jekyll builds the static page it will generate the proper files, directories and references to navigate the page in different languages. This should not be done by Javascript, the page in each language it should be generated.
I made this with a website: https://github.com/worknenjoy/airspace-jekyll
that generate the page https://worknenjoy.github.io/airspace-jekyll/
The language chooser redirects to a pt address to a brazilian portuguese page and the default page is english. The code is open source and it's there.
You can see in Gemfile the gem used is the jekyll-multiple-languages-plugin (https://github.com/Anthony-Gaudino/jekyll-multiple-languages-plugin)
that is responsible to create all you need to have this translation made easier.
You can use multi button for multi button like two button for two languages
and linked them to each other.
for example:
english languages link here
index.html
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">DESIGN</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="services.html">Services<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>logo design</li>
<li>Banner Design</li>
<li>Psd Desgin</li>
</ul>
</li>
<li>contact us</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span><img src="img/fr.png" height="20px" width="20px"></span>English</li>
<li><span><img src="img/eng.png" height="20px" width="20px"></span> French</li>
</ul>
</div>
</nav>
<div class="container">
<h1>Hello Listen Dear !!!!</h1>
<p>Why i listen you?</p>
</div>
french language page
link here
fr_index
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">CONCEPTION</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Accueil</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="fr_services.html">Prestations de service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>création de logo</li>
<li>Conception de bannière</li>
<li>Psd Design</li>
</ul>
</li>
<li>Contactez nous</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span><img src="img/fr.png" height="20px" width="20px"></span>English</li>
<li><span><img src="img/eng.png" height="20px" width="20px"></span> French</li>
</ul>
</div>
</nav>
<div class="container">
<h1>Bonjour Cher Ecoute !!!!</h1>
<p>Pourquoi je t'écoute?</p>
</div>
it's work definatly
thank you
No it's not possible to translate a website using only CSS, since CSS is used for styling only.
For a really smooth and easy translation you can use Cloud Translation, it's a free and open-source project from Angry Monkey Cloud: https://github.com/angrymonkeycloud/CloudTranslation.
It could even modify the Bootstrap style and other styles to support Right-To-Left out of the box, you just have to set the direction of the language to rtl.
You should add reference to jQuery first, then to the CloudTranslation JavaScript file:
<script crossorigin="anonymous" src="https://cdn.amcapi.com/translation/cloudtranslation-1.0.0.min.js"></script>
And add the configuration within the HTML head as follows:
<script type="application/json" id="CloudTranslationConfig">
{
"Settings": {
"DefaultLanguage": "en",
"TranslatorProvider": "Azure", // Could be empty if you want to provide the translations manually
"TranslatorProviderKey": "{Your Microsoft Azure Translator Key}",
"UrlLanguageLocation": "Subdirectory"
},
"Languages": [
{
"Code": "en",
"DisplayName": "English"
},
{
"Code": "de",
"DisplayName": "Deutsch"
}
]
}
</script>
and add your own custom select (dropdown) having the class "CloudTranslationSelect" to display the list of predefined languages.
More information found on https://www.angrymonkeycloud.com/translation
I know its really old post but I fall on this and after much trouble for a project of mine, I found a solution that works.
For two different languages, Greek and English, I added a separate version of each element in every page, one version in Greek and one in English. In each page I put the Greek versions into a div with attribute lang='el' and English versions into a div with lang='en'. I have a function that changes the lang in every div setting display from none to block and viceversa depending on the language.
function allagiglossas() {
const l = document.getElementsByTagName("*");
if(document.querySelector('html').lang === 'en'){
for(i = 0; i<l.length; i++) {
if (l[i].lang === 'el') {
l[i].style.display = 'none';
}
if (l[i].lang === 'en') {
l[i].style.display = 'block';
//location.reload();
}
}
}else{
for(i = 0; i<l.length; i++) {
if (l[i].lang === 'en') {
l[i].style.display = 'none';
}
if (l[i].lang === 'el') {
l[i].style.display = 'block';
}
}
}
}
Another function that sets the HTML lang attribute.
function bilingual() {
if(document.querySelector('html').lang === 'el'){
sessionStorage.setItem("language", "en");
}else{
sessionStorage.setItem("language", "el");
}
document.querySelector('html').setAttribute("lang",sessionStorage.getItem("language"));
allagiglossas();
}
And some code to remember in the browser's session storage what language the user has chosen in order to keep this language when navigating from page to page on my website.
document.querySelector('html').setAttribute("lang",sessionStorage.getItem("language"));
document.getElementById("change").onclick = bilingual;//Με το κουμπί αλλάζει η γλώσσα
document.addEventListener('DOMContentLoaded', allagiglossas);
Of course I added a button in every page and with every click it changes the language.
Hope this will help someone who face the same problem and I will be very grateful if someone tells me if i have something wrong or some way to get things better.

How to add class to an element if a different element on the page has a certain class

jsfiddle.net/8KgRd
I'm trying to select the first header in my main container and add a class to it. But I want this to be dependent on what section of the website they are on.
For example. If they are on the "EAST Core" page, I want the header to be orange.
The HTML is populated by the backend so I can't hardcode the classes in.
HTML
<ul id="mainNav" class="nav navbar-nav">
<li class='linked'>EAST Program
</li>
<li class='active linked'>EAST Core
</li>
<li class='linked'>Get More Involved
</li>
<li class=''>Sponsors & Exhibitors
</li>
<li class=''>Newsroom
</li>
</ul>
<div id="mainbar">
<h1>This is the title I want to add a class to.</h1>
</div>
.
JAVASCRIPT
if ($("#mainNav li:nth-child(2)"): hasClass("active")) {
$("#mainbar h1:first-child").addClass("orangeHead");
};
UPDATE: Solved by:
if ( $("#mainNav li:nth-child(2)").hasClass("active") ) {
$("#mainbar h1:first-child").addClass("orangeHead");
}
One way would be:
$("#mainNav li:nth-child(2).active")
.closest("#mainNav").next()
.find("h1:first-child").addClass("orangeHead");
Another way (your original way with syntax error fixed):
// this is probably the "better" way to do it of the two
if ( $("#mainNav li:nth-child(2)").hasClass("active") ) {
$("#mainbar h1:first-child").addClass("orangeHead");
}
You can get the index of the active navigation element, and then update the other element based on this information, e.g.:
var colorClasses = ['redHead', 'orangeHead', 'blueHead', 'greyHead', 'purpleHead'],
index = $("#mainNav").children(".active").index();
$("#mainbar").addClass(colorClasses[index]);
This is a bit more modular than your code and will be easier to maintain (no need to have different code on different pages, this will work on all pages). Basically the index of the active element just needs to line-up with the index of the colors array for the class that gets added to the #mainbar element.
you can toggle the class of header depending on the active state of you li
$("#mainbar h1:first-child").toggleClass("orangeHead", $("#mainNav li:nth-child(2)").hasClass("active"));
it's interesting how you can have different ways to achieve the same result. Here is another option
toOrange = $("#mainNav").find("li").eq(1);
if( toOrange.is(".active") ){
$("#mainbar > h1").addClass("orangeHead");
}
See JSFIDDLE
I personally give preference to the .eq() method over pseudo classes, which is (arguably) faster in many cases.

Keep added class with JQuery through pages refresh

I have the following JQuery Code concerning my tabs :
$("#onglet>ul>li").click(function(){
$("#onglet ul li").removeClass('Selectionne').addClass("OngletPrincipal");
$(this).removeClass().addClass('Selectionne');
$(this).unbind('mouseenter mouseleave');
it works, but as soon as I click on a tab which leads me to another page, the tab gets its original class.... so its appearance finally doesn't change..
<div id="onglet">
<ul >
<li class="OngletPrincipal">
Accueil
</li>
<li class="OngletPrincipal">
Catalogue
</li>
<li class="OngletPrincipal">
Nous
</li>
<li class="OngletPrincipal">
Contacts
</li>
<li class="OngletPrincipal">
Espace client
</li>
</ul>
</div>
how I am supposed to keep the tab with the "Selectionne" class ?
....
thankkkkkk you !
If you are loading a new static page, and the selected tab is just a link to that page, why isn't the selected tab hard coded into each page? If your serving your pages dynamically, why isn't the server set the selected class when it generates the page? It looks like these tabs are navigating between a set of static html pages, so I'm not sure why you need to set this class after the page loads using JavaScript.
But, if there is some reason I'm missing for setting this after page load you could look into using jquery address or some other history type plugin to persist the tab selection in the url so that you can parse it after the page loads, something like http://fake.com/foo.html#/tab1. Or, without the plugin you could just check which page you selected on load and set the tab that way:
$(document).ready(function(){
var loc = window.location.toString();
var page = loc.substring(
loc.lastIndexOf('/',0) + 1,
loc.length);
$('#onglet>ul>li>a[href$="' + page + '"]').parent().addClass('Selectionne');
});
If you completely reload/load the page in the href, it's another page, hence everything is reloaded and your by js added classes are back to the initial classes.
You will have to remember it serverside, or pass it in a url parameter that you parse in js and see what is requested, activating the class on the right li.
Or dynamically load the content and stay on the same page.

Categories

Resources