I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");
Related
I have created a section including all its content using JS.
const main = document.querySelector('main') ,
new_p = document.createElement('p'),
new_h2 = document.createElement('h2'),
new_div = document.createElement('div'),
new_section = document.createElement('section')
main.appendChild(new_section);
new_section.id = ('section4');
new_section.appendChild(new_div);
new_div.classList.add('landing__container');
new_div.appendChild(new_h2);
new_div.appendChild(new_p);
new_h2.textContent = 'Section 4';
new_h2.id = 'heading4';
new_p.textContent = 'some text goes here'
Then I made an array of all sections (previously created using HTML and newly created using JS).
const sections = Array.from(document.getElementsByTagName("section"))
The problem is that array gets only the sections created with HTML only and can't see the ones created with JS.
here is the array logged to the console (the 3 items in the array are already created with HTML)
(3) [section#section1.your-active-class, section#section2, section#section3]
Anyone can help me how to detect newly created sections with JS?
I tested this code and it's working. JS has no problems here. Maybe you are trying to access sections before the new one is added.
See this snippet:
const main = document.querySelector('main') ,
new_p = document.createElement('p'),
new_h2 = document.createElement('h2'),
new_div = document.createElement('div'),
new_section = document.createElement('section')
main.appendChild(new_section);
new_section.id = ('section4');
new_section.appendChild(new_div);
new_div.classList.add('landing__container');
new_div.appendChild(new_h2);
new_div.appendChild(new_p);
new_h2.textContent = 'Section 4';
new_h2.id = 'heading4';
new_p.textContent = 'some text goes here'
const sections = Array.from(document.getElementsByTagName("section"))
console.log(sections);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script type="module" src="./async-await.js"></script> -->
<script type="module" src="./script.js" defer></script>
</head>
<body>
<main>
<section id="section1"></section>
<section id="section2"></section>
<section id="section3"></section>
</main>
</body>
</html>
I added an event listener to my website which should add a date, time and device-id to the website. These information are included in the filenames of some files located in a directory at the same level as my index.html.
Directory Structure:
- audiofiles
-- date_time_device.wav
-- date2_time2_device2.wav
- scripts
-- scripts.js
- Home.html
Within the head of Home.html I'm calling a addContent() (located in scripts.js) which includes the addEventListener().
This works if I'm inserting hardcoded strings, so it seems that reading from the directory does not work.
It would be great if anybody could steer me into the right direction. Thanks!
Head of Home.html:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/wavesurfer.js"></script>
<script type="text/javascript" src='scripts/scripts.js'> </script>
<script type="text/javascript" src="js/wavesurfer.js"></script>
<script>
addContent();
</script>
<title>Home</title>
</head>
scripts.js:
function addContent() {
document.addEventListener("DOMContentLoaded", function(event) {
var fs = require('fs');
const files = fs.readdirSync('path/to/audiofiles');
for (i=0;i<3;i++) {
var date = files[i].slice(0,10);
var time = files[i].slice(11,19);
var device = files[i].slice(20,-4);
var TheInnerHTML ="";
TheInnerHTML += "<tr><td> blabla" + 3 + " " + String(date)+"</td><td>"+String(time)+"</td></tr>"+String(device)+"</td></tr><br>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;
});
}
How to append the HTML code snippet to HTML iframe using jquery? Actually, I have added an HTML code snippet in MySQL Database using PHP. Now I have fetched that HTML Code snippet and trying to append that HTML code snippet in iframe using jquery.
$( document ).ready(function() {
var snippets='<?php echo $snippets_preview; ?>';
$(function() {
var $iframe = $('#iframehtml');
$iframe.ready(function() {
$iframe.contents().find("body").append(snippets);
});
});
});
But I am getting the following error
Uncaught SyntaxError: Invalid or unexpected token
snippets_preview has the following value in it. when I change the value of snippet_preview. it works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>'.$postdata['snippets_css'].'</style>
<script>'.$postdata['snippets_javascript'].'</script>
</head>
<body>
'.$ContentDecodedHTML.'
</body>
</html>
If you want to embed html code in an iframe you have to do for example:
JAVASCRIPT (class)
<script>
// -------------------------------------------------------- CLASS
var class_iframe = {
// ------------------------------------- STEP 1 (Create an new Iframe)
generateIframe: function(src, targetDOM){
// ---------------- Create iframe
var newIframe = document.createElement('iframe');
newIframe.onload = function(){
class_iframe.getIframe($('.iframehtml').contents());
};
newIframe.src = src;
newIframe.className = "iframehtml";
newIframe.frameBorder = "0";
// ---------------- Insert iframe in DOM
$(targetDOM).replaceWith(newIframe);
},
// ------------------------------------- STEP 2 (Get iframe in this class)
getIframe: function(iframe){
class_iframe.frame = iframe; console.log(class_iframe.frame);
},
// ------------------------------------- STEP 3 (Append in this iframe)
appendIframe: function(targetInIframe, content){
console.log(class_iframe.frame);
$target = class_iframe.frame.find(targetInIframe); console.log($target);
$target.prepend(content);
},
}
// -------------------------------------------------------- ACTION (loadPage)
$(document).ready(function(){
//$("body").prepend(`<div id="insertIframe"></div>`); //Just for the test
class_iframe.generateIframe("your_url_iframe.html", "#insertIframe");
});
</script>
In your html page
<div id="insertIframe"></div>
JAVASCRIPT (for append in your new iframe)
<script>
// -------------------------------------------------------- ACTION (after loadPage)
class_iframe.appendIframe("html", `<div class="insert">Hello world !</div>`);
</script>
I've been having trouble with Firefox not executing JavaScript files that were loaded dynamically via an external script.
Let me explain.
I have the following HTML file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Restive.JS</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="assets/js/load.js"></script>
</head>
<body>
<h1>Loading JavaScript</h1>
</body>
</html>
Inside my load.js file, I have the following code:
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test1.js', 'assets/js/test2.js'];
for (var i = 0; i < list_arr.length; i++) {
loadScript(list_arr[i]);
}
});
And inside test1.js and test2.js, I have console.log('test1.js is loaded!'); and console.log('test2.js is loaded!');.
The problem is that test1.js and test2.js are loaded (I can see both files in the <head> via inspection), but they are never executed (because no messages appear in the console log).
However, when I change the format of script reference in my original HTML by inlining the JavaScript i.e. changing from this:
<script type="text/javascript" src="assets/js/load.js"></script>
to this:
<script>
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test3.js', 'assets/js/test4.js'];
for (var i = 0; i < list_arr.length; i++) {
console.log('i = ' + i);
loadScript(list_arr[i]);
}
});
</script>
Then the scripts are loaded and executed.
I don't see this behaviour in Chrome or Safari, only Firefox. Also, inlining is not an option because this functionality is built-in to a library that users will have to reference via an external link.
Is this a problem that is fixable?
EDIT
I'm on a Mac OSX 10.10.5 using Firefox 46.0.1
I'm building a small application in Play and have an 'outer' template which holds all my CSS and JS imports (jQuery and my main.js file). CSS at the top, JS at the bottom with a body tag in between... pretty basic stuff:
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/foundation.css")">
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
</head>
<body>
#content
</body>
<script src='#routes.Assets.at("javascripts/jquery-1.9.0.min.js")' type="text/javascript"></script>
<script src='#routes.Assets.at("javascripts/index.js")' type="text/javascript"> </script>
</html>
Which is fine.
However, I have page specific javascript functions that should run based on what the page is. So if I go to localhost:9000/test, I want a particular set of functions to run.
If I go to localhost:9000/chips, I want another set of functions to run.
I can't see a neat way of doing this, really, except checking the current page url in the script and executing functions based on that... but the routes file is already doing stuff based on the current page url - seems strange to have to do something so similar twice.
One solution is to put all my scripts at the top and then execute inline scripts in the HTML... but I hate doing things like that.
You have very nice and clear sample available in the... documentation.
Scroll to the bottom and check section: moreScripts and moreStyles equivalents, you have there ready to use samples.
I use a ViewModel approach to solve this issue.
The default ViewModel:
class DefaultPage(
implicit val request: RequestHeader,
implicit val lang: Lang) {
var title: String = null
val styles = mutable.LinkedHashMap.empty[String, Int]
val scripts = mutable.LinkedHashMap.empty[String, Int]
def title(title: String) {
this.title = title
}
def style(style: String)(implicit priority: Int = 500) {
styles.put(style, priority)
}
def script(script: String)(implicit priority: Int = 500) {
scripts.put(script.toString, priority)
}
def translate(message: String, objects: Any*) = Messages(message, objects: _*)
}
Then I have two template tags:
styles.scala.html
#(styles: scala.collection.mutable.Map[String, Int])
#for(style <- styles.toList.sortBy(_._2)) {
<link rel="stylesheet" href="#routes.Assets.at(style._1)" />
}
scripts.scala.html
#(scripts: scala.collection.mutable.Map[String, Int])
#for(script <- scripts.toList.sortBy(_._2)) {
<script async="true" src="#routes.Assets.at(script._1)"></script>
}
My main template:
main.scala.html
#(page: util.view.models.DefaultPage)(content: Html)
#import tags.scripts
#import tags.styles
#page.style("css/vendor/normalize.min.css")(1)
#page.style("css/vendor/formalize.min.css")(1)
#page.style("css/sprites.min.css")(1)
#page.style("css/main.min.css")(1)
#page.style("css/quirks.min.css")(1000)
#page.script("js/vendor/jquery-1.9.1.min.js")(1)
#page.script("js/vendor/jquery.formalize.min.js")(1)
#page.script("js/plugins.min.js")(1)
#page.script("js/main.min.js")(1)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#page.title</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
#styles(page.styles)
<script src="#routes.Assets.at("js/vendor/modernizr-2.6.2.min.js")"></script>
</head>
<body class="#page.lang.code #page.lang.language #page.lang.country">
#content
#scripts(page.scripts)
</body>
And a sub template:
#(page: util.view.models.ContactUsPage)
#page.title(page.translate("contact.us.title"))
#page.style("css/contact-us.min.css")
#page.script("js/vendor/jquery.expandable-1.1.4.js")
#page.script("js/contact-us.min.js")
#main(page) {
}
You can pass your javascript which is specific to a page as template parameter link