Translate web page using javascript - javascript

I tried to translate my web page using js but my code is not working here my code
<div class="navLan">
EN
<!-- <hr> -->
RU
<!-- <hr> -->
UZ
</div>
where user select languages and i used key to give attr to the element like this
<div class="listGroup">
<a href="#row3" class="hvr-grow nav-link lang" key='about'>About</a>
Courses
<a href="#row5" class="nav-link lang" key='reg'>Registration</a>
<a href="#row6" class="nav-link lang" key='news'>News</a>
<a href="#row7" class="nav-link lang" key='feedback'>Feedback</a>
<a href="#row8" class="nav-link lang" key='contact'>Contacts</a>
<div class="hr"></div>
</div>
at the end of the code in script tag i gave translation like this
var arrLang = {
'menu-item_en': {
'about':'About',
'courses':'Courses',
'reg':'Registration',
'news':'News',
'feedback':'Feedback',
'contact':'Contacts'
},
'menu-item_ru': {
'about':'About',
'courses':'Courses',
'reg':'Registration',
'news':'News',
'feedback':'Feedback',
'contact':'Contacts'
},
'menu-item_uz': {
'about':'Biz Haqimizda',
'courses':'Kurslar',
'reg':'Ro\'yxatdan o\'tmoq',
'news':'Yangiliklar',
'feedback':'Fikr-Mulohaza',
'contact':'Aloqa'
}
}
finally my js file here
function change_language(id) {
var lang = id;
document.cookie = "lang=" + lang + ";";
var elementss = document.getElementsByClassName('lang');
var placeholders = document.getElementsByClassName('placeholders');
if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_en') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_en'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_en'][placeholders[g].getAttribute('key')]);
}
} else if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_uz') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_uz'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_uz'][placeholders[g].getAttribute('key')]);
}
} else {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_ru'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_ru'][placeholders[g].getAttribute('key')]);
}
}
};
(function () {
var elementss = document.getElementsByClassName('lang');
var placeholders = document.getElementsByClassName('placeholders');
var inputs = document.getElementsByClassName('inputs');
if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_en') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_en'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_en'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_en'][inputs[j].getAttribute('key')]);
}
} else if (document.cookie.split(';').filter(function (item) {
return item.indexOf('lang=menu-item_uz') >= 0
}).length) {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_uz'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_uz'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_uz'][inputs[j].getAttribute('key')]);
}
} else {
for (let i = 0; i < elementss.length; i++) {
elementss[i].innerHTML = arrLang['menu-item_ru'][elementss[i].getAttribute('key')];
}
for (let g = 0; g < placeholders.length; g++){
placeholders[g].setAttribute('placeholder', arrLang['menu-item_ru'][placeholders[g].getAttribute('key')]);
}
for (let j = 0; j < inputs.length; j++){
inputs[j].setAttribute('value', arrLang['menu-item_ru'][inputs[j].getAttribute('key')]);
}
}
})();
anyone can correct me please?

Most likely when HTML is rendering you probably don't have change_language function, so onclick="change_language(this.id)" binds anything to onclick. Let's try to add addEventListener using javascript.
Here is a working example: https://jsfiddle.net/jugrae2z/

Related

How to connect input filed, button, and function JS

i am learning JS right now, and I don't know how to connect input filed, button, and function. In currently code if I run it i get result of specific string which is in code, so i want to enter random string in input field, and when i click on button get result of that input string.
<input type="text" id="myText" value="String">
<p>Click the "Try it" button</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
let l = str.length;
let k = 0, row, column;
row = Math.floor(Math.sqrt(l));
column = Math.ceil(Math.sqrt(l));
if (row * column < l)
{
row = column;
}
let s = new Array(row);
for (let i = 0; i < row; i++)
{
s[i] = new Array(column);
for (let j = 0; j < column; j++)
{
s[i][j] = 0;
}
}
// convert the string into grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if(k < str.length)
s[i][j] = str[k];
k++;
}
}
// Printing the grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if (s[i][j] == 0)
{
break;
}
document.write(s[i][j]);
}
document.write("</br>");
}
}
let str = "GEEKSFORGEEKS";
gridStr(str);
}
</script>
I got it. Now, you have written unnessesary code there.
<body>
<input type="text" placeholder="Enter Any String" id="str-to-grid">
<br>
<button onClick="stringToGrid()">Try It</button>
<p id="grid-placeholder"></p>
<script>
const Input = document.getElementById("str-to-grid")
const Placeholder = document.getElementById("grid-placeholder")
function stringToGrid() {
//first, let's determine the number of rows and columns we can arrange
//Usually, in grid, x = y, meaning sqrt(length)
var dimension = Math.ceil(Math.sqrt(Input.value.length))
//Now let's arrange our string:
var GridView = []
for ( let stringPtr = 0, dimensionPtr = 0; stringPtr < Input.value.length; stringPtr++)
{
GridView.push(Input.value[stringPtr])
if ( (dimensionPtr + 1)%dimension === 0 )
{
GridView.push("<br />")
}
dimensionPtr++;
}
Placeholder.innerHTML = GridView.join("")
}
</script>
</body>
What this code does is everytime you clicked the button, the placeholder
and the value is taken, and the dimension of the grid is calculated to the upperbound square of the length of the string.
Then is a seperate array, each of the string item is placed, and when the row
ends, a br tag is added. this way, a grid view can be created
This is the improved code: (it will work)
<input type="text" id="myText" value="String">
<p>Click the "Try it" button</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
let l = str.length;
let k = 0, row, column;
row = Math.floor(Math.sqrt(l));
column = Math.ceil(Math.sqrt(l));
if (row * column < l)
{
row = column;
}
let s = new Array(row);
for (let i = 0; i < row; i++)
{
s[i] = new Array(column);
for (let j = 0; j < column; j++)
{
s[i][j] = 0;
}
}
// convert the string into grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if(k < str.length)
s[i][j] = str[k];
k++;
}
}
// Printing the grid
for (let i = 0; i < row; i++)
{
for (let j = 0; j < column; j++)
{
if (s[i][j] == 0)
{
break;
}
document.write(s[i][j]);
}
document.write("</br>");
}
}
let str = "GEEKSFORGEEKS";
gridStr(str);
</script>

Javascript - For loop only affecting last element in array

I'm trying to make a script that gives whatever you're pointing at (that has the class foxrainbowhover) an asynchronous rainbow effect.
I've got it working for the most part but unfortunately it, for some reason, only affects the last element inside of the array. I've ran it all through mentally several times but cannot find a single thing wrong with it. I'm hoping you'll be able to help. Here's what the effect should look like: https://jsfiddle.net/Laoderv6/
(function(){let rainbowhover = document.getElementsByClassName('foxrainbowhover');
let rainbowelements = [];
let hoverinterval = [];
let hovercounters = [];
for(let i = 0; i < rainbowhover.length; i++) {
rainbowelements[i] = spanElementContents(rainbowhover[i]);
}
//Set up the wavey effect with counters.
for(let id = 0; id < rainbowelements.length; id++) {
for(let i = 0; i < rainbowelements[id].length; i++) {
hovercounters[id] = [];
hovercounters[id][i] = 0 + i;
}
}
// Add event listeners for every item classed foxrainbowhover.
for(let id = 0; id < rainbowhover.length; id++) {
rainbowhover[id].addEventListener("mouseenter", function startanimation() {
console.log('hit');
hoverinterval[id] = setInterval(() => {
for(let i = 0; i < rainbowelements[id].length; i++) {
rainbowelements[id][i].style.color = 'hsl(' + (hovercounters[id][i] + Math.floor(i * 1)) + ', 100%, 70%';
console.log(rainbowelements[id]);
hovercounters[id][i]++;
}
}, 8);
}, false);
rainbowhover[id].addEventListener("mouseleave", function stopanimation() {
console.log('agh');
clearInterval(hoverinterval[id]);
for(let i = 0; i < rainbowelements[id].length; i++) {
rainbowelements[id][i].style.color = 'black';
}
}, false);
}
})()
function spanElementContents(element) {
let spans = [];
let chars = [];
chars.push(element.innerText.split(""));
for(let i = 0; i < chars.length; i++){
element.innerHTML = chars[i].map(function(char) {
return '<span>' + char + "</span>";
}).join('');
}
let temphtmlcollection = [].slice.call(element.children)
for(let j = 0; j < temphtmlcollection.length; j++) {
spans.push(temphtmlcollection[j]);
}
return spans;
}
body {
background-color: black;
}
h1 {
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 class="foxrainbowhover">test1</h1>
<h1 class="foxrainbowhover">test111</h1>
<h1 class="foxrainbowhover">test111111</h1>
</body>
</html>
You are constantly resetting your array. You need to initialize it in the outer loop.
Change this:
for(let id = 0; id < rainbowelements.length; id++) {
for(let i = 0; i < rainbowelements[id].length; i++) {
hovercounters[id] = [];
hovercounters[id][i] = 0 + i;
}
}
to this:
for(let id = 0; id < rainbowelements.length; id++) {
hovercounters[id] = [];
for(let i = 0; i < rainbowelements[id].length; i++) {
hovercounters[id].push(i);
}
}
or more simply:
or (let id = 0; id < rainbowelements.length; id++) {
hovercounters[id] = rainbowelements[id].map((_, i) => i);
}
let rainbowhover = document.getElementsByClassName('foxrainbowhover');
let rainbowelements = [];
let hoverinterval = [];
let hovercounters = [];
for (let i = 0; i < rainbowhover.length; i++) {
rainbowelements[i] = spanElementContents(rainbowhover[i]);
}
//Set up the wavy effect with counters.
for (let id = 0; id < rainbowelements.length; id++) {
hovercounters[id] = rainbowelements[id].map((_, i) => i);
}
// Add event listeners for every item classed foxrainbowhover.
for(let id = 0; id < rainbowhover.length; id++) {
rainbowhover[id].addEventListener("mouseenter", function startanimation() {
hoverinterval[id] = setInterval(() => {
for(let i = 0; i < rainbowelements[id].length; i++) {
rainbowelements[id][i].style.color = 'hsl(' + (hovercounters[id][i] + Math.floor(i * 1)) + ', 100%, 70%';
hovercounters[id][i]++;
}
}, 8);
}, false);
rainbowhover[id].addEventListener("mouseleave", function stopanimation() {
clearInterval(hoverinterval[id]);
for(let i = 0; i < rainbowelements[id].length; i++) {
rainbowelements[id][i].style.color = 'black';
}
}, false);
}
function spanElementContents(element) {
let spans = [];
let chars = [];
chars.push(element.innerText.split(""));
for(let i = 0; i < chars.length; i++){
element.innerHTML = chars[i].map(function(char) {
return '<span>' + char + "</span>";
}).join('');
}
let temphtmlcollection = [].slice.call(element.children)
for(let j = 0; j < temphtmlcollection.length; j++) {
spans.push(temphtmlcollection[j]);
}
return spans;
}
h1 {
color: black;
}
<h1 class="foxrainbowhover">test1</h1>
<h1 class="foxrainbowhover">test111</h1>
<h1 class="foxrainbowhover">test111111</h1>
This is what happens when you use asynchronous functions inside a for loop. Here are a couple of ways to fix the problem:
Use let instead of var
Create a function that uses closure and returns a new function
Use a try catch or IIFE block to create a new scope
Let
for (let index = 0; index < 5; index++) {
setTimeout(() => {
console.log(index)
}, 250);
}
Function Wrapper
for (let index = 0; index < 5; index++) {
setTimeout(getFunction(index), 250);
}
function getFunction(index) {
return function() {
console.log(index);
};
}
Try Catch Block
for (let index = 0; index < 5; index++) {
try {
throw index;
} catch (index) {
setTimeout(() => {
console.log(index);
}, 250);
}
}
IIFE Block
for (let index = 0; index < 5; index++) {
(function(index) {
setTimeout(() => {
console.log(index);
}, 250);
})(index);
}

Return parent and his childrens from column and row

I have two functions that return column children and row children, how can I return the parents and their children’s separately, I mean each parent with his childrens.
function cols() {
var c = document.querySelectorAll('.row');
for (var i = 0; i < c.length; i++) {
for (var j = 0; j < c.length; j++) {
c[j].children[i].style.backgroundColor = "orange";
alert(c[j].children[i] / 3 );
}
}
}
cols();
function rows() {
var c = Array.prototype.slice.call(document.querySelectorAll('.row'));
for (var i = 0; i < c.length; i++) {
for (var j = 0; j < c.length; j++) {
c[i].children[j].style.borderColor = "red";
alert(c[i].children[j]);
}
}
}
rows();
fiddle:
I would do it like this:
window.onload=function(){
rows=document.getElementsByClassName("row");
rows.forEach(function(row){
colums=row.children;
colums.forEach(function(col){
alert(col,row);
});
});
}

How to make an auto leveling menu

I want to build a website in which users can create a new menu tab
the system can identified level of the menu
I have written a simple code, but it is still manual, not automatic.
How do I make automatic leveling?
The menu data is stored in the database data, but the system must have the auto leveling menu.
Code:
<%
dataDB data = new dataDB();
dataMainMenu[] daftarMenu1 = data.getDaftarMenuByLevel1();
dataLinkMenu dataLink = new dataLinkMenu();
dataLinkMenu dataLink2 = new dataLinkMenu();
dataLinkMenu dataLink3 = new dataLinkMenu();
dataLinkMenu dataLink4 = new dataLinkMenu();
dataMainMenu dataMenu1 = new dataMainMenu();
dataMainMenu dataMenu2 = new dataMainMenu();
String []y=new String[daftarMenu.length];
dataDB max = new dataDB();
int a=0;
for(int j=0;j<daftarMenu1.length;j++){
dataMenu2 = daftarMenu1[j];
out.write(dataMenu2.getNama());
dataLinkMenu[] daftarSubMenu = data.getLinkSubMenu(dataMenu2.getId());
if(max.getMaxLevel()!=2){
for (int i = 0; i < daftarSubMenu.length; i++) {
dataLink = daftarSubMenu[i];
out.write(dataLink.getSubMenu());
dataLinkMenu[] daftarSubMenu1 = data.getLinkSubMenu(Integer.parseInt(dataLink.getSubMenu()));
if(max.getMaxLevel()!=3) {
for (int k = 0; k < daftarSubMenu1.length; k++) {
dataLink2 = daftarSubMenu1[k];
out.write(dataLink2.getSubMenu());
dataLinkMenu[] daftarSubMenu2 = data.getLinkSubMenu(Integer.parseInt(dataLink2.getSubMenu()));
if(max.getMaxLevel()!=4) {
for (int l = 0; l < daftarSubMenu1.length; l++) {
dataLink3 = daftarSubMenu2[l];
out.write(dataLink3.getSubMenu());
dataLinkMenu[] daftarSubMenu3 = data.getLinkSubMenu(Integer.parseInt(dataLink3.getSubMenu()));
if(max.getMaxLevel()!=5){
for (int m = 0; m < daftarSubMenu1.length; l++) {
dataLink4 = daftarSubMenu3[l];
out.write(dataLink4.getSubMenu());
}
}
}
}
else{
for (int l = 0; l < daftarSubMenu1.length; l++) {
dataLink3 = daftarSubMenu2[l];
out.write(dataLink3.getSubMenu());
}
}
}
} else {
for (int k = 0; k < daftarSubMenu1.length; k++) {
dataLink2 = daftarSubMenu1[k];
out.write(dataLink2.getSubMenu());
}
}
}
} else {
for (int i = 0; i < daftarSubMenu.length; i++) {
dataLink = daftarSubMenu[i];
out.write(dataLink.getSubMenu());
}
}
out.write("<br>");
}%>
any one can help?

convert short jquery to standalone javascript

Can you help me getting this:
$(document).ready(function() {
$("#large").attr("src",bilder[0]);
$.each(bilder, function(i) {
$("#gallery .large").append("<div class='small'><table><tr><td><img src='"+bilder[i]+"' /></td></tr></table></div>");
});
$(".small td").mouseover(function(){
var src = $("img",this).attr("src");
$("#large").attr("src",src);
});
});
I started with this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('large').setAttribute('src', bilder[0]);
for (var i = 0, len = bilder.length; i < len; ++i) {
//???
};
});
That's what I have, but appending and mouseover...no idea.
Hope you can help me "converting" this.
Ok, phew, this comes a little close. Can you try this ?
for (var i = 0, len = bilder.length; i < len; ++i) {
var els = document.getElementById("gallery").getElementsByClassName("large");
for (var j = 0; j < els.length; ++j){
els[i].innerHTML += "<div class='small'><table><tr><td><img src='"+bilder[i]+"' /></td></tr></table></div>";
}
};
...
var smallEls = document.getElementsByClassName("small");
for( var i = 0 ; i < smallEls.length; ++i){
var tds = smallEls[i].getElementsByTagName("td");
for( var j = 0 ; i < tds.length; ++j){
tds[j].onmouseover = function(){
var imgs = document.getElementsByTagName("img");
for( var k = 0 ; k < imgs.length; ++k){
var src = imgs[k].src;
document.getElementById("large").addAttribute("src", src);
}
}
}
}
You can use the property innerHtml of an element te set its content. To append some content, you should use +=
Ex: myElement+= "<p>A new paragraph</p>"
FYI, solved it like this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('large').setAttribute('src', bilder[0]);
for (var i = 0, len = bilder.length; i < len; ++i) {
var els = document.getElementById("gallery").getElementsByClassName("large");
for (var j = 0; j < els.length; ++j){
els[j].innerHTML += "<div class='small'><table><tr><td onmouseover='document.getElementById(\"large\").setAttribute(\"src\", \""+bilder[i]+"\");'><img src='"+bilder[i]+"' /></td></tr></table></div>";
}
};
});

Categories

Resources