Changing language with toggle button bootstrap - javascript

I'm learning to code with bootstrap, html, css, js. And I'm wondering if it's possible to modify the language of my webpage with a toggle button?
I'm using bootstrap toggle which can set events like this:
<input id="toggle-event" type="checkbox" data-toggle="toggle">
<div id="console-event"></div>
<script>
$(function() {
$('#toggle-event').change(function() {
$('#console-event').html('Toggle: ' + $(this).prop('checked'))
})
})
</script>
And I also saw this thread on stack about changing languageusing element.lang.
And I'm not able to 'mix' the two methods to change the language on deman simply by clicking on the toggle button, and I don't understand why =/
Here's my attempt:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-toggle.min.js"></script>
<body class="fr" id="test1">
<p lang="en">
Je parle la baguette
</p>
<p lang="fr">
I speak the baguette
</p>
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-size="large" data-onstyle="info" data-offstyle="info" data-on="Fr" data-off="En">
<!--<script>
$(function() {
$('#toggle-event').bootstrapToggle({
on: document.body.className= 'fr',
off: document.body.className = 'en'
});
})
</script>-->
<script>
$(function() {
$('#toggle-event').change(function() {
$('#test1').body('Toggle: ' + $(this).prop('checked')).className='en'
});
});
</script>
</body>
CSS:
body.en :lang(en) {
display: none;
}
body.fr :lang(fr){
display: none;
}
https://jsfiddle.net/mttkchfc/1/

There are a number of issues with your attempt.
The most obvious one is that the languages are the wrong way round. Your "en" section contains French text, and the "fr" one contains English text!
The CSS is also mangled compared to the example you cited - look more carefully at how the :lang part is constructed in the original. In the original example, it is used to hide the opposite language, whereas you're using it to hide the same language. You've got the concept the wrong way round.
Also, this line is total nonsense:
$('#test1').body('Toggle: ' + $(this).prop('checked')).className='en'
There's no such jQuery function as ".body" - if you look in your browser console (press F12, if you didn't know, to open the Developer Tools in most modern desktop browsers), you'll see this error reported when you click on the toggle.
"classname" is a native JS property, it doesn't work on jQuery objects, which this would be if it was valid
If it was possible to use a function like "body" to set the body content, all it would do is set the content of the whole <body> section to "Toggle: true", or similar. This would be useless.
Even if all of that were to be ignored, and it were capable of setting the class, it only ever sets it to English - you wouldn't be able to change back to French.
The example in the link you gave, using document.body.className works perfectly well. You just need to vary the class name depending on whether the toggle is on or off. I have chosen to store the class names in data- attribute values "true" and "false", which of course correspond to the string representation of a boolean. This means we can neatly use the value of the "checked" property of the toggle to fetch the correct data- attribute value and use that as the new class name, without any tedious if or switch statements:
CSS
body.en :lang(fr) {
display: none;
}
body.fr :lang(en){
display: none;
}
HTML
<body class="en">
<p lang="fr">
Je parle la baguette
</p>
<p lang="en">
I speak the baguette
</p>
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-size="large" data-onstyle="info" data-offstyle="info" data-on="English" data-off="French" data-true="en" data-false="fr" >
</body>
JS
$(function() {
$('#toggle-event').change(function() {
document.body.className = $(this).data($(this).prop("checked").toString());
});
});
P.S. Your JSFiddle didn't work at all because you didn't include jQuery, your scripts were in the wrong section, and you have to reference bootstrap etc as external resources - the inline links you provided were pointing to local resources which don't exist in a JSFiddle environment. I've fixed that for you, plus updated it so it works as you intend:
https://jsfiddle.net/mttkchfc/4/

Related

How detect actual language of webpage translated via Google translate?

I need to detect the translated language and ideally make some class maybe to body. After that via this class edit CSS of webpage. I have no problem with solutions with jQuery or pure JavaScript.
I need this because different languages has different length of words and this can make me problem with design. I need solved this like
.language_cz .some_class{
font-size: 14px;
}
.language_en .some_class{
font-size: 16px;
}
I make this translate via https://gtranslate.io/. This is pure Google translate.
Code of translate is:
<div class="obal_mutace">
<span class="aktualni_mutace">CZ</span>
<div class="blok_mutace_in">
<span data-id="CZ" class="polozka_mutace_in">CZ</span>
<span data-id="EN" class="polozka_mutace_in">EN</span>
<span data-id="DE" class="polozka_mutace_in">DE</span>
<span data-id="RU" class="polozka_mutace_in">RU</span>
<span data-id="FR" class="polozka_mutace_in">FR</span>
<span data-id="IT" class="polozka_mutace_in">IT</span>
<span data-id="PT" class="polozka_mutace_in">PT</span>
<span data-id="ES" class="polozka_mutace_in">ES</span>
<div id="google_translate_element2"></div>
<script type="text/javascript" src="funkce/transl_init.js?v=1.0.1"></script>
<script type="text/javascript" src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit2"></script>
</div>
in "transl_init.js" I have:
function googleTranslateElementInit2() {new google.translate.TranslateElement({pageLanguage: 'cs',autoDisplay: false}, 'google_translate_element2');}
/* <![CDATA[ */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('6 7(a,b){n{4(2.9){3 c=2.9("o");c.p(b,f,f);a.q(c)}g{3 c=2.r();a.s(\'t\'+b,c)}}u(e){}}6 h(a){4(a.8)a=a.8;4(a==\'\')v;3 b=a.w(\'|\')[1];3 c;3 d=2.x(\'y\');z(3 i=0;i<d.5;i++)4(d[i].A==\'B-C-D\')c=d[i];4(2.j(\'k\')==E||2.j(\'k\').l.5==0||c.5==0||c.l.5==0){F(6(){h(a)},G)}g{c.8=b;7(c,\'m\');7(c,\'m\')}}',43,43,'||document|var|if|length|function|GTranslateFireEvent|value|createEvent||||||true|else|doGTranslate||getElementById|google_translate_element2|innerHTML|change|try|HTMLEvents|initEvent|dispatchEvent|createEventObject|fireEvent|on|catch|return|split|getElementsByTagName|select|for|className|goog|te|combo|null|setTimeout|500'.split('|'),0,{}))
/* ]]> */
I used it on my webpage project http://www.kalimera-recko.cz/. I used Google translate in head of web on the left from search input.
If I understand your question correct you want to style your page according to the used language.
On your page you set the language attribute on the html tag.
<html class="js" style="height: 100%;" lang="cs">
So you can address it in your css with this:
html[lang="cs"] .some_class
[EDIT]__________________
A cookie is set
"googtrans" to the value /cs/en if translated to englisch and to te value /cs/de if translated to german.
You can find out the value of the cookie with javascript or jQuery
document.cookie
It returns a string where you need to search for the "googtrans" value.
You can get the language with this:
var cookie = document.cookie;
var position = cookie.indexOf("googtrans");
var language = cookie.substring(position+10, position + 16);
This code can be optimized if you search for the end of the value ';' instead of using fixed numbers.
But this will do what you need.
You may also should use a try/catch and see if the cookie exists because it doesn't exist for your original language.

jQuery color scheme changer

I have seen a lot of websites that contain a color switcher through which a user can select/pick any color, and the whole page will change accordingly. Below are a few example links....
http://csmthemes.com/themes/beta/static/
http://magna-themes.com/demos/html/flatapp/index.htm
http://envato.nestolab.com/Batekh/style-1/image-slider-version/index-one-page.html
http://ronseta.com/Roof/index_02.html
What I want: I want the same color scheme, but the problem is that I am that expert to create it on my own, so I want the basic logic and some code to start, I have a basic knowledge of JavaScript and jQuery. If there are any free plugins related to that then please share the link, or share some code through which I can start building my own..
Following "http://magna-themes.com/demos/html/flatapp/index.htm"
0.create multiple css files by color
style/colors/default.css
style/colors/green.css
style/colors/red.css
style/colors/pink.css
1.you create a link to css with an id like color-switcher
<link rel="stylesheet" type="text/css" href="style/colors/default.css" id="color-switcher">
2.you create a menu of color picker
<div id="demo-wrapper">
<h2>COLORS:</h2>
<ul>
<li class="green" data-path="style/colors/green.css"></li>
<li class="red" data-path="style/colors/red.css"></li>
<li class="pink" data-path="style/colors/pink.css"></li>
</ul>
<div class="clear"></div>
<p data-path="style/colors/default.css">Restore Default Scheme</p>
</div>
3.you change the path of your link using javascript
$('#demo-wrapper ul li').on('click', function(){
var path = $(this).data('path');
$('#color-switcher').attr('href', path);
});
The basic theory goes like this! You create a theme with buttons, forms, controls etc.. Styling of the elements are usual. If I developed a theme where the user can select a color scheme, I would add a special class to every element which I want the user to modify. for an example :
I've the following html element.
<input type='button' value='submit' class='yourStyle specialClass'>
I've got the following style
.yourStyle{
** Style **
}
I'll use the following sample jQuery code to change the color scheme.
$('document').ready(function(){
$('colorSchemeChoser').click(function(){
$('.specialClass').css('background-color','sampleColor');
})
})
Above is a basic code to start your development.
Try changing the stylesheet dynamically using jQuery (preferred) or Javascript. Each stylesheet has styles defines a particular theme. To make your code look a little professional, try using data-* HTML 5 attributes to change stylesheet.
Below is an example:
Html:
<button id="grayscale" data-theme="style.css">Original</button>
<button id="grayscale-2" data-theme="style2.css">Custom</button>
And js:
$("button[data-theme]").click(function() {
$("head link[rel=stylesheet]").attr("href", $(this).data("theme"));
}
Hope this helps. Let me know if you need any further clarifications. Thanks!
this answer is a demonstration of how 'you can change the background color from user input'
If, however, you wanted to use a completely different 'theme', I would suggest creating different css files, and modifying the style link in your head section (via jquery/javascript) to point to each 'theme'.
This jquery would do the basics for you, changing the background color on three inputs.
$(document).ready(function(){
$('#changeColor').click(function(){
var red= $('#red').val();
var green = $('#green').val();
var blue = $('#blue').val();
var op = $('#opacity').val();
$('html').css("background","rgba("+red + ","+green+","+blue+","+op+")");
});
});
input[type="number"] {
width: 100px;
height: 50px;
}
#red{
background:red;
}
#green{
background:green;
}
#blue{
background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="1" id="red" value="255"/>
<input type="number" step="1" id="green" value="255" />
<input type="number" step="1" id="blue" value="255"/>
<input type="number" step="0.1" id="opacity" value="1" />
<button id="changeColor">GO</button>
On your HTML you can add a list with class-name and path to your different css files...
You change your css files dynamically with jquery...
If you want only to change colours check this site out:
http://www.marcofolio.net/webdesign/create_a_better_jquery_stylesheet_switcher.html
good luck
I don't know why this hasn't been mentioned, but jqueryui has a themeroller, with several pre-made themes, and you can make your own. (http://jqueryui.com/themeroller/)
Easiest solution here is to implement a themeswitcher like the one here: https://github.com/harborhoffer/Super-Theme-Switcher
Of course, you could write your own switcher as well, basically you're just switching the src of the jqueryui stylesheet...
You stated you already understand how to switch the style sheet. You could use cookies to make the switch persist between page loads.
This article goes over the concept (also check out the date on it :D)
http://alistapart.com/article/alternate
Here's a really simple solution I put together that I think does what I think you're trying to accomplish.
HTML
<h1>Color Picker</h1>
<input type='text' class="colorPicker"/>
JS
$(".colorPicker").spectrum({
color: "#ff0000",
change: function(color) {
// convert the color output to a usable hex format
color = color.toHexString();
// set the css of your target element to the chosen color
$("body").css({"background-color":color});
}
});
http://jsfiddle.net/edhebert/tbptwz67/
In this demo I'm using the Spectrum Color Picker. It's a free, really easy to use plugin available at https://bgrins.github.io/spectrum/
I'm using a really basic color picker, but Spectrum has all sort of customization options.
Hope this helps.
I just found a cool jQuery plugin from Github which allow you to switch color schemes of the website.
HTML:
<head>
<link href="dist/jquery.colorpanel.css" rel="stylesheet">
<link href="skins/default.css" id="cpswitch" rel="stylesheet">
</head>
<body>
<div id="colorPanel" class="colorPanel">
<a id="cpToggle" href="#"></a>
<ul></ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="dist/jquery.colorpanel.js"></script>
</body>
JavaScript:
$('#colorPanel').ColorPanel({
styleSheet: '#cpswitch',
animateContainer: '#wrapper',
colors: {
'#4B77BE': 'skins/default.css',
'#16a085': 'skins/seagreen.css',
}
});
Repository: ColorPanel .
Demo & Documentation: Demo.

Show 2nd div when radio button checked

Im trying to make a contact form where people will check either "one way" ticket or "roundtrip".
The first "one way" is checked when user reach the contact form and one(1) date field is shown, but if "roundtrip" is checked i want a 2nd date field to be shown with a return date.
Any ideas?
Simply observe the onchange event for the radio button. When it reaches you can check weather single trip or round trip is selected and then show / hide the div with the return date fields.
<!DOCTYPE html>
<head>
<script>
function hdl_change(e) {
document.getElementById('date2').style.visibility =
e.checked && e.id == 'opt_2' ? 'visible' : 'hidden';
}
</script>
</head>
<body>
<form name="myForm">
<input id="opt_1" type="radio" name="trip" value="oneway" onchange="hdl_change(this)"> One way<br>
<input id="opt_2" type="radio" name="trip" value="round" onchange="hdl_change(this)"> Roundtrip<br>
</form>
<div id="date1"> date 1 stuff ...</div>
<div id="date2" style="visibility:hidden"> date 2 stuff ...</div>
</body>
</html>
You would need to use javascript and on-event handlers to accomplish that, as such dependent/binding functionality doesn't come with the regular html form elements (To avoid confusion: same goes for it's potential children).
This answer will give you a pretty good hint how to do it as it answers a question related to a similar problem/request: https://stackoverflow.com/a/5137316/1093284
Update:
As you don't seem very experienced, here's a most simplistic example:
<!-- include jquery.js library first (http://jquery.com/) -->
<script src="jquery.js"></script>
<!-- then work the magic -->
<script>
$(document).ready(function(){
$('#inputB').hide;
$('#checkboxA').click(
function(e){
$('#inputA').show;
$('#inputB').hide;
});
$('#checkboxB').click(
function(e){
$('#inputB').show;
$('#inputA').hide;
});
});
</script>
And if you're fit enough to go pro with jQuery, check the other answer here on this page at https://stackoverflow.com/a/11743381/1093284
Last but not least, I think the answer here at https://stackoverflow.com/a/11743482/1093284 provides the best solution, as it's small and does not require a full-blown 32kb javascript library. On the other hand, inline javascript is actually a no-go. Whatever... it's the users that count and they will prefer a quicker-loading page over nicely coded stuff behind the curtains.

Setting DIV width and height in JavaScript

I have a div with id="div_register". I want to set its width dynamically in JavaScript.
I am using this following code:
getElementById('div_register').style.width=500;
but this line of code isn't working.
I also tried using the units px like the following, still no luck:
getElementById('div_register').style.width='500px';
and
getElementById('div_register').style.width='500';
and
getElementById('div_register').style.width=500px;
but none of this code is working for me.
I don't know what's going wrong.
I am using Mozilla Firefox.
EDIT
<html>
<head>
<title>Untitled</title>
<script>
function show_update_profile() {
document.getElementById('black_fade').style.display='block';
//document.getElementById.('div_register').style.left=((window.innerWidth)-500)/20;
document.getElementById('div_register').style.height= "500px";
document.getElementById('div_register').style.width= '500px';
//alert('kutta');
document.getElementById('div_register').style.display='block';
document.getElementById('register_flag').value= 1;
document.getElementById('physical_flag').value= 0;
document.getElementById('cultural_flag').value= 0;
document.getElementById('professional_flag').value= 0;
document.getElementById('lifestyle_flag').value= 0;
document.getElementById('hobby_flag').value= 0;
//alert(window.innerWidth);
}
</script>
<style>
.white_content {
display:none;
}
</style>
</head>
<body>
<div id="main">
<input type="button" onclick="javascript:show_update_profile();" id="show" name="show" value="show"/>
</div>
<div id="div_register">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
welcome
</td>
</tr>
</table>
</div>
</body>
</html>
The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:
document.getElementById('div_register').setAttribute("style","width:500px");
For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:
document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";
Thus, the most cross-browser compatible example for you would be:
document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width='500px';
I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers!
document.getElementById("div_register").setAttribute("class","wide");
.wide {
display:block;
width:500px;
}
.hide {
display:none;
}
.narrow {
display:block;
width:100px;
}
Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.
This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
Fix the typos in your code (document is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and you'll be fine. #jmort's advice is good - simply set up 2 css classes that you switch between in javascript - it'll make things easier.
You might also check out element.addEventListener for assigning event handlers to your elements.
The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.
If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox
Condensed example:
<html>
<head>
<script type="text/javascript">
function show_update_profile() {
document.getElementById('div_register').style.height= "500px";
document.getElementById('div_register').style.width= "500px";
document.getElementById('div_register').style.display='block';
return true;
}
</script>
<style>
/* just to show dimensions of div */
#div_register
{
background-color: #cfc;
}
</style>
</head>
<body>
<div id="main">
<input type="button" onclick="show_update_profile();" value="show"/>
</div>
<div id="div_register">
<table>
<tr>
<td>
welcome
</td>
</tr>
</table>
</div>
</body>
</html>
Be careful of span!
myspan.styles.width='100px' doesn't want to work.
Change the span to a div.
You have to use document. The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content,
know more
document.getElementById('div_register').style.width='500px';

How to style a Javascript snippet

I want to embed this Javascript snippet (webform from AWeber) into my website:
<script type="text/javascript" src="http://forms.aweber.com/form/49/522310949.js"></script>
My site uses the style p { line-height: 1.5em; }. Unfortunately this is also applied to the Javascript snippet and makes it look stupid.
How can I tell the Javascript snippet to use a line-height of 1em instead of 1.5em?
I tried this but it doesn't work:
<p style="line-height: 1em;">
<script type="text/javascript" src="http://forms.aweber.com/form/49/522310949.js"
</script>
</p>
I also considered using Javascript (document.getElementById('p').style.lineHeight = '1 em';) to change the CSS, but as I understand Javascript modifies the whole website and not only one element...
Can you please help?
Thanks in advance!
div.af-form {
line-height: 1em;
}
In case you need more styling, I see that your generated block also uses these styles: af-header, af-body, af-footer, af-element and af-textWrap.
However, if you need a more universal solution, refer to #Pointy's answer.
Putting the form inside a <p> does not make sense, as <p> cannot contain block-level elements. Use a <div> instead:
<div style='line-height: 1em;'>
<script src = " ... "></script>
</div>
As #Max implicitly noted, it'd be "nicer" to add CSS to style the content.
You can use Firebug or the Chrome/Safari developer tools to examine the styles of "live" page elements. That can help you figure out the reasons that particular elements look a particular way, and it also lets you play around with alterations to the styles.
edit maybe something like:
div.af-form p { line-height: 1em; }

Categories