Scrollspy Uikit 3 framework and count up - uikit

i am a beginer in frontend and javascript hard for me :( I want to make count numbers with component scrollspy uikit 3 without jquery https://getuikit.com/docs/scrollspy
I made like this, but it's not working
<span id="number"></span>
<script>
UIkit.scrollspy('#number', 'inview', function () {
const countUp = new CountUp('number', 0, 1000 );
countUp.start();
});
</script>

I created a script for this.
var util = UIkit.util;
var el = util.$('#heading');
var textIndex = 0;
UIkit.scrollspy(el, {repeat: true, delay: 100});
util.on(el,'inview', function (){
function counter( start, end, duration) {
let current = start,
range = end - start,
increment = end > start ? 1 : -1,
step = Math.abs(Math.floor(duration / range)),
timer = setInterval(() => {
current += increment;
el.textContent = current;
if (current == end) {
clearInterval(timer);
}
}, step);
}
counter(0, 100, 3000);
});
util.on(el, 'outview', function(){
el.textContent = 0;
});
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/js/uikit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/js/uikit-icons.min.js"></script>
<section class="uk-section uk-section-primary" uk-height-viewport="offset-top: true">
<div class="uk-container">
<div class="uk-text-center">
<h1 >SECTION 1</h1>
Source Code for Number Increment
</div>
<div class="uk-text-center uk-margin-medium-top">
<a class="uk-link-reset" href="#section" uk-scroll>Scroll</a>
</div>
</div>
</section>
<section class="uk-section uk-section-secondary" id="section">
<div class="uk-container">
<h1 class="uk-text-center" id="heading">0</h1>
</div>
</section>
You need to listen inview and outview event. Here is the method:
UIkit.util.on(element, 'event', function(){
//your code will be here here
});

Related

Chart.js 4.0.1 Uncaught ReferenceError: Chart is not defined

I wrote an AJAX Javascript code for my ESP32 datalogger which worked so far using old versions of Chart.js. The website hosted by the ESP32 is not working anylonger if I use a more recent of Chart.js.
The error message I caught is:
Uncaught ReferenceError: Chart is not defined at datalogin.html
The line in the code involved is this one
const myChart = new Chart(ctx, config);
Something in the interpretation seems to occur at a very early stage. But I could not identify what. See code below.
I already tried different Chart.js repository in order to have it working. It had absolutly no influence. I actively looked using different browser regarding this specific problematic and I could not find any way of solving this problem.
Thanks a lot for your support
<!DOCTYPE html>
<html lang="en">
<head>
<title>EFM Meter loggin interface</title>
<link rel="icon" type="image/x-icon" href="lightning.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="https://github.com/cdnjs/cdnjs/blob/master/ajax/libs/Chart.js/4.0.1/chart.js" ></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns#2.0.1/dist/chartjs-adapter-date-fns.bundle.js"></script>
<style>
.jumbotron {
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>Elektrofeldmeter Data Logging Page</h1>
</div>
<div class="container">
<div class="border border-2 m-2">
<div class="row">
<div class="col-sm-12 ">
<div class="container-sm">
<canvas id="myChart" style="" height="152"></canvas>
</div>
</div>
</div>
</div>
<div class="row">
<div class="border border-2 m-2">
<div class="col-sm-12">
<h3> Parameters setup</h3>
</div>
</div>
<div class="border border-2 m-2">
<div class="row">
<div class="col-sm-12">
<label for="customRange1" class="form-label" id="labelPWM">PWM of motor: 190</label>
<input type="range" class="form-range" min="0" max="190" step="1" value="190" onchange="rangeValue(this)" id="customRange1">
</div>
<div class="col-sm-6">
<label for="customRange2" class="form-label" id="labelYmin">Y min: -5000</label>
<input type="range" class="form-range" min="-5000" max="5000" step="1" value="-5000" onchange="rangeY()" id="Ymin">
</div>
<div class="col-sm-6">
<label for="customRange2" class="form-label" id="labelYmax">Y max: +5000 0</label>
<input type="range" class="form-range" min="-5000" max="5000" step="1" value="5000" onchange="rangeY()" id="Ymax">
</div>
<div class="col-sm-12">
<button type="button" class="btn btn-primary" onclick="saveAs()">*.CSV</button>
</div>
</div>
</div>
</div>
</div>
<script>
function rangeValue(element) {
console.log(element.value);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/pwm?value="+element.value, true);
xhr.send();
document.getElementById("labelPWM").innerHTML = "PWM of motor: " + element.value;
};
function rangeY() {
myChart.options.scales.y.max = document.getElementById('Ymax').value;
myChart.options.scales.y.min = document.getElementById('Ymin').value;
myChart.update();
};
function clkOrientation(element) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/clk?value="+element.checked, true);
xhr.send();
}
const animation = { };
const config = {
type: 'line',
data: {
datasets: [{
borderColor: '#fc9905',
borderWidth: 2,
radius: 0,
data: 0
}
]
},
options: {
animation,
interaction: {
intersect: false
},
plugins: {
legend: false
},
scales: {
x: {
type: 'time',
title: {
display: true,
text: 'time',
color: '#000000',
font: {
size: 20
}
},
ticks :
{
color: '#000000',
font: {
size: 12
}
}
},
y: {
type: 'linear',
title: {
display: true,
text: 'Electrical field [V/m] # PWM=190',
color: '#000000',
font: {
size: 20
}
},
ticks :
{
color: '#000000',
font: {
size: 12
}
}
}
},
plugins: {
title: {
display: true,
text: 'Electrical field value [V/m]'
}
}
}
};
Chart.defaults.font.size = 20;
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, config);
function addData(chart, data) {
for (var i = 0 ; i < data.length; i++){
chart.data.datasets[0].data.push({"x":data[i].x,"y":(data[i].y-32.671)/0.48025});
};
chart.update();
};
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var txt = this.responseText;
var array = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
addData(myChart,array);
}
};
xhttp.open("GET", "readEFM", true); //Handle readADC server on ESP32
xhttp.send();
};
setInterval(function() {
getData();
}, 5000);
txt = '[{"x":1662921606250,"y":35.71},{"x":1662921606450,"y":35.61},{"x":1662921606650,"y":35.70},{"x":1662921606850,"y":35.74},{"x":1662921607050,"y":35.78},{"x":1662921607250,"y":35.45},{"x":1662921607450,"y":35.65},{"x":1662921607650,"y":35.66},{"x":1662921607850,"y":35.78},{"x":1662921608050,"y":35.76}]';
const myArr = JSON.parse(txt);
addData(myChart,myArr);
myChart.update();
function saveAs(){
let csvContent = "data:text/csv;charset=utf-8,";
for (var i = 0 ; i < myChart.data.datasets[0].data.length; i++){
csvContent+=myChart.data.datasets[0].data[i].x + "," + myChart.data.datasets[0].data[i].y + "\n";
}
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "EFM_log.csv");
document.body.appendChild(link);
link.click();
};
</script>
</body>
</html>

return isTrusted false

I'm writing my first web component with Stencil.
It's a pills component published here : https://github.com/reservoir-dogs/rp-pills
The component code's :
import { Component, Prop, Watch, Event, EventEmitter } from '#stencil/core';
#Component({
tag: 'rp-pills',
styleUrl: 'rp-pills.scss',
shadow: false
})
export class RpPills {
#Prop() items: any[] = [];
#Prop() displayProperty: string;
#Prop({ mutable: true }) value: any;
#Prop() class: string;
#Prop() theme: string = 'default';
#Prop() emptyMessage: string = 'No item';
classes: string;
#Event() valueChange: EventEmitter;
onClick(item: any) {
this.value = item;
this.valueChange.emit(this.value);
}
#Watch('class')
#Watch('theme')
watchHandler() {
this.classes = `nav nav-pills ${this.theme} ${this.class}`;
}
render() {
if (this.items.length > 0)
return (
<ul class={this.classes}>
{this.items.map((item) =>
<li onClick={() => this.onClick(item)} class={this.value === item ? 'active' : ''} >
<a>{item[this.displayProperty]}</a>
</li>)}
</ul>
);
else
return (
<ul class={this.classes}>
<li class="empty">
<a>{this.emptyMessage}</a>
</li>
</ul>
);
}
}
This test work fine :
it('should work with a list of items and selected item', async () => {
const cmp = new RpPills();
cmp.valueChange = {
emit: () => { }
};
const spy = jest.spyOn(cmp.valueChange, 'emit');
cmp.onClick({name:'Coucou'});
expect(spy).toHaveBeenCalledWith({ name: 'Coucou' });
});
But my HTML sample and an integration in Ionic App does not work and return the following message : {"isTrusted":false}
HTML sample :
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/rppills.js"></script>
</head>
<style>
.orange .active a {
background-color: #ff0000;
}
.orange a {
background-color: #ff6a00;
}
div {
float: left;
clear: both;
}
</style>
<body>
<div>
<rp-pills display-property="name" class="nav-pills-bordered" theme="orange">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills display-property="name" class="nav-justified">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills display-property="name" class="nav-pills-bordered nav-justified">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills class="nav-pills-bordered">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills empty-message="Aucun message" class="nav-pills-bordered">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills>
</rp-pills>
<span></span>
</div>
<script>
var cmps = document.querySelectorAll('rp-pills');
for (var i = 0; i < cmps.length; i++) {
var cmp = cmps[i];
if (cmp.attributes.length > 0 && cmp.attributes[0].name == 'display-property') {
cmp.value = { 'name': 'Coucou' };
cmp.items = [cmp.value, { 'name': 'Comment ca va ?' }, { 'name': 'Au revoir' }];
cmp.addEventListener('valueChange', (event) => { alert(JSON.stringify(event)); });
}
}
setInterval(() => {
var cmps = document.querySelectorAll('rp-pills');
var spans = document.querySelectorAll('span');
for (var i = 0; i < cmps.length; i++) {
if (cmps[i].value != undefined)
spans[i].innerText = cmps[i].value.name;
}
}, 1000);
</script>
</body>
</html>
2 errors
I tried to do that :
<rp-pills [items]="jeux" [(value)]="partie.jeu"></rp-pills>
The event of my Stencil component's :
is not compliant with angular two-way binding
contain a property 'detail' where there is my value
Use in Ionic App
HTML code
<rp-pills [items]="jeux" [value]="partie.jeu" (valueChange)="jeuChange($event.detail)"></rp-pills>
TypeScript code
jeuChange(jeu: Jeu) {
this.partie.jeu = jeu;
}

Ajax to call on same page within column

Hey I am working with AJAX to display live CSV data on my webpage, Currently my AJAX script on button click. But I want it to show the data without refreshing or clicking the button in grid view but I am unable to figure it out.
Here's my attempt :-
$(document).ready(function() {
$('#load_data').click(function() {
$.ajax({
url: "sample.csv",
dataType: "text",
success: function(data) {
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < employee_data.length; count++) {
var cell_data = employee_data[count].split(",");
table_data += '<tr>';
for (var cell_count = 0; cell_count < cell_data.length; cell_count++) {
if (count === 0) {
table_data += '<th>' + cell_data[cell_count] + '</th>';
} else {
table_data += '<td>' + cell_data[cell_count] + '</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>Click Load Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1 align="center">Please Click on Load Data</h1>
<br />
<div align="center">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
</div>
<br />
<div id="employee_table">
</div>
</div>
</div>
</body>
</html>
Easy! All you need to do is call the data load function on page ready rather than adding it as a .click() callback:
$(document).ready(function() {
$.ajax({
url: "sample.csv",
dataType: "text",
success: function(data) {
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < employee_data.length; count++) {
var cell_data = employee_data[count].split(",");
table_data += '<tr>';
for (var cell_count = 0; cell_count < cell_data.length; cell_count++) {
if (count === 0) {
table_data += '<th>' + cell_data[cell_count] + '</th>';
} else {
table_data += '<td>' + cell_data[cell_count] + '</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Click Load Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<div id="employee_table">
</div>
</div>
</div>
</body>
</html>

How can I use JSONP to bypass an error with XMLHttpRequest?

Can someone help me to use JSONP so I can bypass this error:
XMLHttpRequest cannot load https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/24332988/ranked?season=SEASON4&?api_key=***********. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
I am having trouble understanding on how to use it.
Here is the code I have right now which gives me the error above. How can I fix this?
//ap.js
var summonerLookUp = function () {
// DECLARE URIs
var nameUri = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
var statUri = 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/';
var statEnd = '/ranked?season=SEASON4&';
// Expose API Key for demo purposes
var apiKey = '?api_key=******************************';
// Grab summoner names;
var summOne = $('#summOne').val();
var summTwo = $('#summTwo').val();
// declare divIds that need to be modified later;
var divIds = {
summoner : '',
sLevel : 'Summoner Level : ',
sId : 'Summoner ID: ',
champKills : 'Champion Kills: ',
death : 'Death Total: ',
assist : 'Assist Total: ',
kda : 'Avg KDA: ',
win : 'Wins: ',
loss : 'Losses: ',
minions : 'Minion Kills: ',
turrets : 'Turret Kills: '
};
// Declare general errorhandler
var errorHandler = function () {
alert('Sorry, please try again.');
};
// Must fetch summoner info first to get basic summoner data
var fetchSummonerStats = function (summoner) {
$.ajax({
url: nameUri + summoner + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summData) {
summData = summData[summoner];
// attach .summoner property to summData for divIds later
summData.summoner = summoner;
console.log('SUMM DATA >>', summData);
fetchDetail(summData);
},
error: errorHandler
});
};
// Declare secondary ajax call to fetch stats
// provide summonername an data to attach
var fetchDetail = function (summoner) {
$.ajax({
url: statUri + summoner.id + statEnd + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summStats) {
// include previous data to attach for divIds
summStats.id = summoner.id;
summStats.summoner = summoner.summoner;
summStats.level = summoner.summonerLevel;
attachStats(summStats);
},
error: errorHandler
});
};
var attachStats = function(summStats) {
var summNumber;
/*
attach a 1 or 2 based on summonername;
if summStats.summoner === xkouki,
summNumber = 1 else it must be summTwo
*/
if (summStats.summoner === summOne) {
summNumber = 1;
} else if (summStats.summoner === summTwo) {
summNumber = 2;
} else {
return errorHandler();
}
// change summoner to summoner as saved in riot api
summStats.summoner = summStats.name;
for (var divId in divIds) {
/*
if divId === summoner
val = 'xkouki';
*/
var val = summStats[divId];
/*
add summonerNumber to the current key in divIds
if divId === summoner
and summNumber === 1
id = summoner1;
etc ...
*/
var id = divId + summNumber;
/*
attach prefix to actual value
if divid === summoner
divIds.summoner = ''
innerHtml = '' + xkouki
*/
document.getElementById(id).innerHtml = divIds[divId] + val;
}
};
// make sure both values exist
if (!summOne || !summTwo) {
alert('Please make sure you have an entry for summoner one & two');
} else {
// loop through this array using forEach and fetchSummoner
[summOne, summTwo].forEach(function (summoner) {
fetchSummonerStats(summoner);
});
}
};
$(document).ready(function() {
$('#list').click(function() {
$('.list').fadeToggle("fast");
});
});
<!DOCTYPE html>
<html>
<head>
<title>League Stats</title>
<link rel="stylesheet" type="css/text" href="styles.css"/>
<link rel="stylesheet" type="css/text" href="font.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<link href='http://fonts.googleapis.com/css?family=Trade+Winds' rel='stylesheet' type='text/css'>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<header class="title">
<h1>League of Legends Face Off</h1>
<input id="summOne" placeholder="summoner name"/>
<input id="vs" type="button" value="VS" onclick="summonerLookUp();" />
<input id="summTwo" placeholder="summoner name"/>
</header>
<div class="one">
<div id="summoner1"></div>
<div id="sLevel1"></div>
<div id="sID1"></div>
<div id="champKills1"></div>
<div id="death1"></div>
<div id="assist1"></div>
<div id="kda1"></div>
<div id="win1"></div>
<div id="loss1"></div>
<div id="minions1"></div>
<div id="turrets1"></div>
</div>
<div class="logo"><img class="vs" src="vs.png"></div>
<div class="two">
<div id="summoner2"></div>
<div id="sLevel2"></div>
<div id="sID2"></div>
<div id="champKills2"></div>
<div id="death2"></div>
<div id="assist2"></div>
<div id="kda2"></div>
<div id="win2"></div>
<div id="loss2"></div>
<div id="minions2"></div>
<div id="turrets2"></div>
</div>
<button id="list">summoner names</button>
<div class="list" style="display: none;">
xkouki | theoddone | le groot | renesisbuddy | azoh | gripex | bestriven na
<br/>
dyrus | kingtrick | voyboy | robertxlee | iamgosu | balls | fabbbyyy | azingy | megazero
</div>
</div>
</body>
</html>

Backbonejs Marionette simple chat example

As a marionnette beginner, I am trying to make a simple chat application using Collection and CollectionViews.
My collection won't have a fetch method since the messages only come from a particular event.
In the piece of code below my click event is not catched and I wonder why.
Should the 'send message' event be handled by the Collection view ?
Do I need to call App.chat.show(MsgListView) to display the messages ?
TBox.module("ChatApp", function(ChatApp, App, Backbone, Marionette, $, _) {
App.addRegions({
chat: "#chat-messages",
});
// Models
// ------
MsgEntry = Backbone.Model.extend({});
// Collections
// -----------
MsgCollection = Backbone.Collection.extend({
model: MsgEntry
})
// VIews
// -----
MsgView = Backbone.Marionette.ItemView.extend({
template: '#chat-entry-template',
});
MsgListView = Backbone.Marionette.CollectionView.extend({
itemView: MsgView,
events: {
"click #chat-send-btn": "handleNewMessage"
},
handleNewMessage: function(data) {
console.log("CLICK" + data);
},
});
// Init & Finalize
// ---------------
ChatApp.addInitializer(function() {
var msgCollection = new MsgCollection({});
var msgEntry = new MsgEntry({'msg': 'Hello World'});
msgCollection.add(msgEntry);
var msgListView = new MsgListView({collection: msgCollection});
});
});
HTML template
<body>
<!-- templates -->
<script type="text/template" id="status-view-template">
<div>Connecting ...</div>
</script>
<script type="text/template" id="chat-entry-template">
Hello <%= msg =>
</script>
<div id="app">
<div id="sidebar">
<div id="chat">
<h3>Chat</h3>
<div id="chat-messages">
</div>
<div id-"chat-input">
<input type="text" name="msg" />
<button id="chat-send-btn">Send</button>
</div>
</div>
</div>
<!-- main -->
<div id="page">
</div>
<div>
</body>
Ok I made it work with App.chat.show(msgListView);
Also the events hash only takes car of the ItemView events, not other dom events.
// Init & Finalize
// ---------------
ChatApp.addInitializer(function() {
App.vent.trigger("app:started", "ChatApp");
var msgCollection = new MsgCollection([{foo :'bar', foo: 'lol'}]);
var msgListView = new MsgListView({collection: msgCollection});
// render and display the view
App.chat.show(msgListView);
});

Resources