Good day all,
i need a little bit of help migrating from i18next jquery 1.11.1 to version 3.0.0
currently this is my setup
<!-- Core JS files -->
<script type="text/javascript" src="../js/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="../js/i18next.min.js"></script> (v1.11.1)
$(function(){
// i18next Configuration
// -------------------------
var namespaces = ["nav" ,"common" ];
var options = {
ns: {
namespaces: namespaces,
defaultNs: namespaces[0]
},
resGetPath: '../assets/locales/__ns__/__lng__.json',
debug: false,
load: 'unspecific',
detectLngQS: 'lang',
fallbackLng : 'en',
cookieName: 'applang',
//cookieExpirationTime : ,
useLocalStorage: false,
cookieDomain: '*.mydomain.com',
useCookie: true,
lngWhitelist: ['en','es', 'de', 'fr']
};
i18n.init(options ,function (err,t) {
$('body').i18n(); // Init 18n
});
})
and when i want to load additional namespace i do this
var namespaces = ["newFile"];
i18n.loadNamespaces(namespaces, function (err, t) {
// init i18n
$('body').i18n();
.............. other stuff in here
})
but when i try to use the latest i18next v3 with the jquery-i18next (https://github.com/i18next/jquery-i18next) keeping the same logic i get errors on the loadNamespaces function (Uncaught TypeError: namespaces.forEach is not a function), below is the new setup
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next/3.0.0/i18next.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-i18next/0.0.2/i18next-jquery.min.js" ></script>
i18next
.use(i18nextXHRBackend)
.init({
lng: 'de',
backend: {
loadPath: '../assets/locales/{{lng}}/{{ns}}.json'
}
}, function(err, t) {
jqueryI18next.init(i18next, $);
$('.body').localize();
});
var namespaces = ["newFile"];
i18n.loadNamespaces(namespaces, function (err, t) {
// init i18n
$('body').localize();
.............. other stuff in here
})
For anyone interested here is my solution
<script type="text/javascript" src="../assets/js/core/libraries/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18next.min-v3.3.1.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/jquery-i18next.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextLocalStorageCache.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextIntervalPluralPostProcessor.min.js"></script>
$(function(){
// i18next Configuration
// -------------------------
var namespaces = ["nameSpace1" ,"NameSpace2" ],
cacheOptions = {
// turn on or off
enabled: true, // prefix for stored languages
prefix: 'i18next_res_',
expirationTime: 1*24*60*60*1000 // expiration
},
lngDetectionOption = {
//order and from where user language should be detected
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
//keys or params to lookup language from
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLocalStorage',
//cache user language on
caches: ['localStorage','cookie'],
// optional expire and domain for set cookie
cookieMinutes: 365*24*60, // 1 year
cookieDomain: 'myDomain',
// optional htmlTag with lang attribute, the default is:
htmlTag: document.documentElement
},
i18nextoptions = {
compatibilityJSON: 'v2',
debug: true,
whitelist : ['en','es', 'de', 'fr'],
ns: namespaces,
load: 'unspecific',
fallbackLng : 'en',
detection: lngDetectionOption,
backend: {loadPath: '../assets/locales/{{ns}}/{{lng}}.json'},
//cache : cacheOptions
};
i18next
.use(i18nextBrowserLanguageDetector)
.use(i18nextXHRBackend)
.use(Cache)
.use(i18nextIntervalPluralPostProcessor)
.init(i18nextoptions, function (err, t) {
var options = $().jqueryI18nextOptions;
//init jquery-i18next
jqueryI18next.init(i18next, $,options);
$('body').i18n(); // Init 18n
})
})
Related
I've been having issues using google translator directly on my sveltekit web app using the following code
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
// googleTranslateElementInit()
</script>
I've tried several approaches, for example putting the code in <svelte:head></svelte:head> but yet it's kept appearing and disappearing.
Please how can I achieve this,
Note I'm using Static adapter, thanks in advance
I had to load the script manually after mounting of component. It works with SvelteKit too.
onMount(() => {
loadTranslate()
setTimeout(function () {
googleTranslateInit()
}, 3000)
})
function googleTranslateInit() {
const checkIfGoogleLoaded = setInterval(() => {
if (google != null && google.translate != null && google.translate.TranslateElement != null) {
clearInterval(checkIfGoogleLoaded)
googleTranslateElementInit()
}
}, 1000)
}
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element')
}
function loadTranslate() {
loading = true
if (browser) {
const domElement = document.createElement('script')
domElement.setAttribute('src', '//translate.google.com/translate_a/element.js')
domElement.onload = () => {
loadedTranslate = true
}
document.body.appendChild(domElement)
}
}
</script>
<template>
<div id="google_translate_element" class="mb-2"></div>
</template>
I have a problem with laravel livewire. I think the problem is really simple, but I can not solve it. Let me explain everything.
I have a daterangepicker (LitePicker), he works perfect, but I want when user select date range value to set this value to the property and filter data. My problem is that I can't set value to the property.
my Js Code:
#push('scripts')
<script type="text/javascript">
document.addEventListener('livewire:load', function() {
var field = document.getElementById('filter-date-range')
var dateRange;
var picker = new Litepicker({
element:field,
format: 'DD/MM/YYYY',
lang: 'de',
singleMode: false,
onSelect: function(start, end) {
#this.dateRange = start
}
});
})
</script>
#endpush
#this directive is compiled to
onSelect: function(start, end) {
window.livewire.find('').dateRange = start
}
I think the problem is here, because parameter which is passed to find function is empty or the id of the component is missing, and I don't know how to fix it.
Now here is the the error I received when date is selected:
index.js:30 Uncaught TypeError: Cannot read property '$wire' of undefined
at Livewire.value (index.js:30)
at e.onSelect (book_keeping:695)
at e.r.Litepicker.setDateRange (main.js:12)
at e.onClick (main.js:12)
at HTMLDocument.<anonymous> (main.js:12)
As you can see I use push directive so here is the code where I load the scripts
#livewireScripts
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.7.3/dist/alpine.min.js" defer></script>
<script type="text/javascript" src="{{asset('js/app.js')}}"></script>
#stack('scripts')
Also I tried with events wire:model and wire:change without success.
I used like this
document.addEventListener('livewire:load', function() {
var field = document.getElementById('date-from')
var picker = new Litepicker({
element:field,
lang: 'de',
autoApply: false,
singleMode: true,
numberOfColumns: 1,
numberOfMonths: 1,
showWeekNumbers: true,
format: "D MMM, YYYY",
dropdowns: {
minYear: 1990,
maxYear: null,
months: true,
years: true,
},
setup: (picker) => {
picker.on('selected', (date1, date2) => {
Livewire.emit('from-selected', date1)
});
}
});
})
than in livewire
protected $listeners = ['from-selected' => 'fromSelected'];
public function fromSelected($from){
$this->from = $from;
$this->resetPage();
}
Try registering AlpineJS after Livewire Scripts.
I'm working with fullcalendar, and the google calendar api where I get my events out and want to deliver them to my fullcalendar as json since the fullcalendar event accept that as a datasource and automatically renders them into the calendar.
I have my html file which includes a number of ressources and a jQuery script that creates the calendar:
<html>
<head>
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='fullcalendar/lib/jquery.min.js'></script>
<script src='fullcalendar/lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
<script type='text/javascript' src='fullcalendar/gcal.js'></script>
<script src='fullcalendar/lang/da.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: 'calendarData.js'
});
});
</script>
</head>
<body>
<div id="calendar"></div>
</body>
</html>
Notice the events: that takes the json object in. I have a json file with identical hardcoded json object as the one i'm trying to create and that works fine. But something fails/is wrong in the following javascript file.
calendarData.js
var CLIENT_ID = 'id';
var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadCalendarApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Google Calendar client library. List upcoming events
* once client library is loaded.
*/
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', listUpcomingEvents);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
});
var json = {};
request.execute(function(resp) {
var events = resp.items;
json.json = [];
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
json.json.push({id : i+1, title : event.summary, start : event.start.dateTime, end : event.end.dateTime, desc : event.description});
}
}
});
return json;
}
As you might see this is very close to the api calendar javascript quickstart apart from the json at the end. I would like the script to return a json object to the fullcalendar but this doesn't work, so how could I change this if possible?
When i stringify and alert the object I can see that the object created is the same as the previously mentioned json file that does work.
Edit:
The json file i'm talking about and which data can be used looks like this:
[{"id":"1","title":"Test 1","start":"2016-05-26","end":"2016-05-26T16:30:00","allDay":false},{"id":"2","title":"Test 2","start":"2016-05-26","end":"2016-05-26T17:00:00","allDay":false},{"id":"3","title":"Test 3","start":"2016-05-27T08:00:00","end":"","allDay":false}]
When I stringify and alert the object it looks like this:
var myObject = JSON.stringify(json);
alert(myObject);
{"json":[{"id":1,"title":"ghhgfgh","start":"2016-05-26T14:30:00+02:00","end":"2016-05-26T15:30:00+02:00"}]}
Your problem is here:
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: 'calendarData.js'
});
});
The "events" can't get a javascript file as an input nor as a direct json string. You can give it an array of events, a URL or a function.
I guess you intended to feed the "events" with the results of listUpcomingEvents() function.
You can do it that way (just make sure your you add the calendarData.js as script src in your HTML file as well):
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: function(start, end, timezone, callback){
callback(listUpcomingEvents());
},
});
});
To interract between JS / JSON object you've to use:
JSON.stringify()
JSON.parse()
Reference are here and here
For example: JS > JSON > JS
var x = {
y: 'hello',
z: 1
};
console.log(JSON.parse(JSON.stringify(x)));
convert it into JSON object like this:
var Jobj = JSON.parse(your_string_data);
The issue I have is this:
On my website, I pull my blog content from an external source which, the first time it's called upon to display, has to use a HTTP request to get. Also, the blog posts are written in Markdown, and I have to parse this to HTML.
I have this controller that goes out and gets the posts from github, decodes them, and parses them into HTML:
app.controller('content', function ($scope, github, html) {
github.getAllContent().then(function (res) {
var files = [];
res.data.forEach(function (obj) {
github.getFile(obj.path).then(function (res) {
res.data.content = marked(window.atob(res.data.content));
res.data.name = res.data.name.slice(0, res.data.name.indexOf('.'));
files.push(res.data);
})
});
$scope.files = files;
});
$scope.renderHtml = html.renderHtml;
});
html is this service
app.service('html', function ($sce) {
this.renderHtml = function (string) {
return $sce.trustAsHtml(string);
}
});
that allows me to insert the HTML into each HTML element like this: <elem>ng-bind-html="renderHtml(info) </elem>".
Whenever I do this, however, LaTeX content isn't rendered. I have configured MathJax to recognize $ ... $ as delimiters, but no matter what happens, I can't seem to get anything to render. I have even called the MathJax.Hub.Typeset() function or set the typeset callback in the MathJax.Hub.Queue function and it doesn't work. Is this because of the markdown parser I use or how the data is encoded? Or is it just a matter of typesetting the MathJax at the right time?
In this project, I use Angular ui-router, if that has anything to do with it.
I have used this (mathjaxBind.directive.js) directive in my project for MathJax and its working for me:
Plunker
mathjaxBind.directive.js
'use strict';
MathJax.HTML.Cookie.Set("menu", {});
MathJax.Hub.Config({
skipStartupTypeset: true,
messageStyle: "none",
extensions: ["tex2jax.js", "mml2jax.js", "MathML/content-mathml.js", "MathML/mml3.js"],
jax: ["input/MathML", "input/TeX", "output/SVG", "output/HTML-CSS", "output/NativeMML", "output/CommonHTML"],
"HTML-CSS": {
availableFonts: [],
styles: {".MathJax_Preview": {visibility: "hidden"}},
showMathMenu: false
},
"SVG": {
availableFonts: [],
styles: {".MathJax_Preview": {visibility: "hidden"}},
showMathMenu: false
},
"NativeMML": {
availableFonts: [],
styles: {".MathJax_Preview": {visibility: "hidden"}},
showMathMenu: false
},
"CommonHTML": {
availableFonts: [],
styles: {".MathJax_Preview": {visibility: "hidden"}},
showMathMenu: false
}
});
MathJax.Hub.Register.StartupHook("HTML-CSS Jax Ready", function () {
var FONT = MathJax.OutputJax["HTML-CSS"].Font;
FONT.loadError = function (font) {
MathJax.Message.Set("Can't load web font TeX/" + font.directory, null, 2000);
document.getElementById("noWebFont").style.display = "";
};
FONT.firefoxFontError = function (font) {
MathJax.Message.Set("Firefox can't load web fonts from a remote host", null, 3000);
document.getElementById("ffWebFont").style.display = "";
};
});
(function (HUB) {
var MINVERSION = {
Firefox: 3.0,
Opera: 9.52,
MSIE: 6.0,
Chrome: 0.3,
Safari: 2.0,
Konqueror: 4.0,
Unknown: 10000.0 // always disable unknown browsers
};
if (!HUB.Browser.versionAtLeast(MINVERSION[HUB.Browser] || 0.0)) {
HUB.Config({
jax: [], // don't load any Jax
extensions: [], // don't load any extensions
"v1.0-compatible": false // skip warning message due to no jax
});
setTimeout('document.getElementById("badBrowser").style.display = ""', 0);
}
})(MathJax.Hub);
MathJax.Hub.Register.StartupHook("End", function () {
var HTMLCSS = MathJax.OutputJax["HTML-CSS"];
if (HTMLCSS && HTMLCSS.imgFonts) {
document.getElementById("imageFonts").style.display = ""
}
});
angular.module('fsaApp')
.directive('mathjaxBind', function () {
return {
restrict: "A",
controller: ["$scope", "$element", "$attrs", function ($scope, $element, $attrs) {
$scope.$watch($attrs.mathjaxBind, function (value) {
//$($element).parent().find('math').wrap("<script type='math/mml'></script>");
$element.html(value);
MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
});
}]
};
});
Controller:
app.controller('MainCtrl', function($scope) {
$scope.info='<script type=\"math/mml\"><math>\n<mstyle displaystyle=\"true\">\n<mtext> N </mtext>\n<msub>\n<mrow>\n<mtext> O </mtext>\n</mrow>\n<mrow>\n<mn> 2 </mn>\n</mrow>\n</msub>\n</mstyle>\n</math></script>';
$scope.info2='<script type=\"math/mml\"><math>\n<mstyle displaystyle=\"true\">\n<mtext> C </mtext>\n<msub>\n<mrow>\n<mtext> H </mtext>\n</mrow>\n<mrow>\n<mn> 4 </mn>\n</mrow>\n</msub>\n</mstyle>\n</math></script>';
});
Library:
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
in HTML:
<div mathjax-bind="info"></div>
<div mathjax-bind="info2"></div>
Is it possible to create an object inside RequireJS?
Because, in this way, FunctionA is visible inside the Click event:
require(["library1", "library2"], function (obj1) {
$('#loginButton').click(function () {
functionA();
});
functionA() {
obj1.value;
}
});
But if i do something like this, it doesn't work:
var library = new library();
require(["library1", "library2"], function (obj1) {
$('#loginButton').click(function () {
library.functionA();
});
});
function library() {
this.functionA = function () {
obj1.value;
}
}
or
var library = new library();
$('#loginButton').click(function () {
library.functionA();
});
functionA() {
require(["library1", "library2"], function (obj1) {
this.functionA = function () {
obj1.value;
}
});
}
Is this possible?
I'm not sure why your explicit example is not working. However, I would suggest ensuring that you make jQuery a dependency in your require statement.
The following is using dojo, which uses an AMD environment like RequireJS. I just wanted to make sure that I was able to load multiple modules for my example and RequireJS has not modules with it like dojo does.
I was able to get your second example working by fixing the dependencies.
var library = new library();
require(["dojo/dom", "jquery"], function(dom, $) {
$('#button').click(function() {
library.functionA();
});
});
function library() {
this.functionA = function() {
console.log("hello");
}
}
<script>
var dojoConfig = {
parseOnLoad: false,
isDebug: true,
async: 1,
packages: [{
name: "jquery",
location: "//code.jquery.com",
main: "jquery-1.11.3.min"
}]
};
</script>
<!-- Include the dojo 1.10.4 CDN -->
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<main>
<button id="button" type="button">Click me</button>
</main>