Sending data from html.index to functions.js file - javascript

Currently, I am stuck on working with a .html file which needs to send over data to a javascript file with functions. It looks as follows:
Data
let data = [
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]
HTML part calling javascript functions file with
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<title>Metabase Dashboard Carousel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="./src/carousel.js"></script>
</head>
<body onLoad="createFrames('test!')">
<button class="btn btn-primary " onclick=autoRun()>Start</button>
<button class="btn btn-primary " onclick=pause()>Pause</button>
</body>
</html>
Function which is called
function createFrames(text) {
console.log(text);
for(var i in data)
prepareFrame(data[i][0], data[i][1]);
};
Calling the function does give me a print of test! on the .html console with Mozilla inspector. However, running the rest of the script or actually using the data variable as input in the body onLoad function does not work.
How does this come and what would be a fix?
Also, not directly related what is a good way to load files between related .js / .yml / .json as when running the code in .html gives back that require is not defined?
Thanks for the help!

If you are able to modify your approach and are wanting to define the runtime data that will be used by the onload function you might try an approach like this. This uses an anonymous self executing function to run the prepareFrame commands once the DOM has been fully loaded. The data is supplied as an argument to the anonymous function and other functions can be defined within this scope so as to keep the whole thing neat.
(function(data){
const d=document;
// emulate actual functions with simple console cmds for testing only
const prepareFrame=(a,b)=>{
console.log('prepareFrame(%s,%s)',a,b)
};
const autoRun=(e)=>{console.log(e.target);return true};
const pause=(e)=>{console.log(e.target);return true}
d.addEventListener('DOMContentLoaded',()=>{
data.forEach(a=>{
prepareFrame(a[0],a[1])
});
d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
switch(this.dataset.task){
case 'start':return autoRun(e);
case 'pause':return pause(e);
}
}))
})
})([
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]);
<button class='btn btn-primary' data-task='start'>Start</button>
<button class='btn btn-primary' data-task='pause'>Pause</button>
For instance:
<!DOCTYPE html>
<html>
<head>
<meta content='text/html;charset=utf-8' http-equiv='Content-Type' />
<meta content='utf-8' http-equiv='encoding' />
<title>Metabase Dashboard Carousel</title>
<link href='//cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We' crossorigin='anonymous' />
<script src='//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script src='./src/carousel.js'></script>
</head>
<body>
<button class='btn btn-primary' data-task='start'>Start</button>
<button class='btn btn-primary' data-task='pause'>Pause</button>
</body>
<script>
(function(data){
const d=document;
// emulate actual functions with simple console cmds for testing only
const prepareFrame=(a,b)=>{
console.log('prepareFrame(%s,%s)',a,b)
};
const autoRun=(e)=>{console.log(e.target);return true};
const pause=(e)=>{console.log(e.target);return true}
d.addEventListener('DOMContentLoaded',()=>{
data.forEach(a=>{
prepareFrame(a[0],a[1])
});
d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
switch(this.dataset.task){
case 'start':return autoRun(e);
case 'pause':return pause(e);
}
}))
})
})([
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]);
</script>
</html>

Related

Uncaught ReferenceError: _k is not defined

I am trying to import a module I made, however, I cannot access the function. Js tells me that it is not defined even though it is in the html.
<!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>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/#kagarisoft/csc/dist/css/common.min.css"
/>
<style>
.flex-buttons {
display: flex;
gap: 10px;
}
</style>
<!-- my module -->
<script type="module" src="https://cdn.jsdelivr.net/gh/Neyunse/kquery/dist/kquery.browser.min.js"></script>
<!-- <script type="module" src="https://cdn.jsdelivr.net/gh/Neyunse/kquery/dist/kquery.module.min.js"></script> -->
</head>
<body>
<div class="kg__container">
<!-- All content -->
<div class="flex-buttons">
<button id="hot" data-tag="hot" class="kg__button">
Get coffe hot list
</button>
<button id="iced" data-tag="iced" class="kg__button">
Get coffe iced list
</button>
<button id="clear" class="kg__button" disabled>Clear List</button>
</div>
<ul id="coffe"></ul>
</div>
<script src="./main.js"></script>
</body>
</html>
main.js
_k().load(() => {
_k('#hot').event('click', async () => {
_k("#hot").removeClass("kg-primary")
const { tag } = _k('#hot').getDataSet()
_k('#coffe').removeChildrens()
const r = await _k().remote(`https://api.sampleapis.com/coffee/${tag}`).get();
r.map(r => {
_k('#coffe').insertHTML(`<li><b>${r.title}:</b> ${r.description}</li>`)
})
_k('#hot').disableElement(true)
_k('#iced').disableElement(false)
_k('#clear').disableElement(false)
})
_k('#iced').event('click', async () => {
const { tag } = _k('#iced').getDataSet()
_k('#coffe').removeChildrens()
const r = await _k().remote(`https://api.sampleapis.com/coffee/_k{tag}`).get();
r.map(r => {
_k('#coffe').insertHTML(`<li><b>_k{r.title}:</b> _k{r.description}</li>`)
})
_k('#iced').disableElement(true)
_k('#hot').disableElement(false)
_k('#clear').disableElement(false)
})
_k('#clear').event('click', async () => {
_k('#coffe').removeChildrens()
_k('#iced').disableElement(false)
_k('#hot').disableElement(false)
_k('#clear').disableElement(true)
})
console.log(_k('button').getElements())
})
this module is a mini jquery clone I made, however, I'm having problems accessing it from a .js
the compiler I used was https://rollupjs.org/
I have the feeling that it is a problem when exporting the module, however, I don't know what could be the problem.
my module src: https://github.com/Neyunse/kquery/tree/master/src/lib
By looking at the code of the kquery library, you should either expose the _k object as a global variable inside your script:
window._k = _k;
Or store the result of the IIFE in a global variable:
const _k = (function () {
'use strict';
class Remote {
...
return _k;
})();
Otherwise, the variable _k only lives inside the private scope of the IIFE and cannot be accessed in the outer scopes.
Update: you can also do it by passing the --name parameter to rollup (preferred):
npx rollup main.js --file ../../dist/kquery.browser.min.js --format iife --name _k
This will automatically export the _k variable as a global object accessible to all scripts.

data.indexOf is not a function error in [tabulator]

data.indexOf is not a function error in Tabulator JavaScript Library.
Complete error message:
[Error] TypeError: data.indexOf is not a function. (In 'data.indexOf("{")', 'data.indexOf' is undefined)
load (tabulator.js:6075)
_loadInitialData (tabulator.js:7971)
_create (tabulator.js:7841)
(anonieme functie) (tabulator.js:7756)
And warning:
Table Not Initialized - Calling the redraw function before the table is initialized may result in inconsistent behavior, Please wait for the `tableBuilt` event before calling this function
I used the setup as described in the doc, browser based so tabulator.js and tabulator.css in the location that is in the html. Nothing else done.
My HTML:
<!DOCTYPE html>
<html lang="nl">
<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">
<link rel="stylesheet" href="css/tabulator.css">
<!-- <link rel="stylesheet" href="css/tabulator.css.map"> -->
<link rel="stylesheet" href="css/layout.css">
<link rel="stylesheet" href="css/style.css">
<script defer src="js/tabulator.min.js"></script>
<script defer src="js/crud.js"></script>
<script defer src="js/data.js"></script>
<script defer src="js/assess.js"></script>
<title>DMMA</title>
</head>
<body>
<main id="home">
<h1 class="center-text dark-blue-text">Datamanagement Maturity Assessment</h1>
<div id="entree" class="container"></div>
<div class="output container"></div>
</main>
</body>
</html>
My javascript in assess.js:
document.addEventListener('DOMContentLoaded', async function() {
// the assObj is the data of assessment objects I want to retrieve
const assObj = new dataProvider;
// Use Tabulator
assObj.get('api.php/records/AssmntPlusObjects')
// .then(async dataArray => displayRecords(dta, false)) // Works!
.then(dataArray => {
let table = new Tabulator("#entree", {
data: dataArray,
autoColumns: true
})
})
.catch(err => displayError(err, null))
});
The assObj.get goes to a fetch class that gets the data from a MySQL database that gets the data via a PHP generic API. That all works.
The data array with objects is transformed to JavaScript object OK. The Tabulator gives the above error.
The site is on an internet provider host, I don't want to run another MySQL locally.
Any suggestions? Setup wrong?
dataArray is either empty or undefined. Check by console.log(dataArray)
Found the culprit! I needed get to the records in dataArray with
data: dataArray.records,
That's it!
I found that amazing because in a custom table function I built with the data (the displayRecords(dataArray, false)) it just worked without the .records property.
Thanks for putting me on the track of the contents of the dataArray.

Some HTML nodes are not created while I execute function.Cannot read property 'childNodes' of null,

Why I am getting this error? I guess some of my HTML nodes are not created why I try to call the doSearch method. It's actually happening only second time I call this function.
I'm using React and calling this function inside componentDidUpdate lifecycle method.
Here is my HTML file where I load my script inside
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="//csr.inspsearchapi.com/lib/infospace.search.js">
</script>
<link rel="stylesheet" href="./static/style/styles.css" />
</head>
<body>
<div class="container"></div>
<script src = "bundle.js"></script>
</body>
Here is my function:
componentDidUpdate(prevProps) {
const signature = this.props.signature ? this.props.signature.response.data : '';
window.insp.search.doSearch({
query: this.state.searchText,
searchUrlFormat: this.state.searchText,
signature,
page: 1,
containers: {
'top': {id:'topResults'},
'related': {id:'relatedResults'},
},
});
}

Webpage is displaying curly braces from expressions using Angular1.4

As I'm new to Angular, I expect to run in to issues however this issue seems to be repeating itself off and on.
As I'm following a tutorial on learning Angular here, I was learning about how to use expressions.
What I'm attempting to do is access an gem's attributes and display them on the webpage. However, the object values are not being accessed and it is just displaying as so:
{{store.product.name}}
${{store.product.price}}
{{store.product.description}}
Add to Cart
Where as I want it to display as:
Dodecahaderon
$2.95
. . .
Add to Cart
I thought it may be due to the videos using Angular1.2 and I'm using 1.4 however I'm not sure. What am I doing wrong and how can I properly display the object attributes?
Here is the code:
(function () {
var app = angular.module('store', []);
app.controller('StoreController', function(){
this.product = gem;
});
var gem = {
name: 'Dodecahaderon',
price: 2.95,
description: '. . . ',
canPurchase = true,
soldOut = true
};
})();
<!DOCTYPE html>
<html ng-app="store">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
</head>
<body ng-controller="StoreController as store">
<div ng-hide="store.product.soldOut">
<h1>{{store.product.name}}</h1>
<h2>${{store.product.price}}</h2>
<p>{{store.product.description}}</p>
<button ng-show="store.product.canPurchase">Add to Cart</button>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Your angular library is not referenced correctly. Open your console window and make sure the angular script reference is actually working.
Currently gem is definied outside the scope of the controller. Also, as gem as an object you must change = to :
You need to change your code to this and it works
(function () {
var app = angular.module('store', []);
app.controller('StoreController', function(){
this.item = {
name: 'Dodecahaderon',
price: 2.95,
description: '. . . ',
canPurchase : true,
soldOut : true
};
});
})();
And your html to this:
<!DOCTYPE html>
<html ng-app="store">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-controller="StoreController as store">
<div ng-hide="store.product.soldOut">
<h1>{{store.item.name}}</h1>
<h2>${{store.item.price}}</h2>
<p>{{store.item.description}}</p>
<button ng-show="store.item.canPurchase">Add to Cart</button>
</div>
</body>
</html>
Also, you may need to replace your reference to angular from <script type="text/javascript" src="angular.min.js"></script> to <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></sc‌​ript>

CamanJS image manipulation, strange error

i'm using CamanJS to do some images manipulation with javascript, and I have two similar really simple scripts, the first works well, the second not (and this is the script i need working).
This is the first working:
<!DOCTYPE html>
<html lang="en">
<head>
<title>CamanJS Testing Playground</title>
<script type="text/javascript" src="caman.full.min.js"></script>
</head>
<body>
<button onclick="filtraPhoto();">MODIFICA</button><br />
<img id="smallImage" />
<script>
var immagine;
var smallImage = document.getElementById('smallImage');
smallImage.src = "test1_600.jpg";
immagine = Caman("#smallImage", function () {});
function filtraPhoto() {
immagine.brightness(10).contrast(500).render(function () {
alert("Done!");
});
}
</script>
</body>
</html>
This is the second not working, it return in firebug the error: TypeError: this.c.pixelData is undefined
<!DOCTYPE html>
<html lang="en">
<head>
<title>CamanJS Testing Playground</title>
<script type="text/javascript" src="caman.full.min.js"></script>
<script>
var immagine;
function carica()
{
var smallImage = document.getElementById('smallImage');
smallImage.src = "test1_600.jpg";
immagine = Caman("#smallImage", function () {});
}
function filtraPhoto() {
immagine.brightness(10).contrast(500).render(function () {
alert("Done!");
});
}
</script>
</head>
<body>
<button onclick="carica();">carica immagine</button><br />
<button onclick="filtraPhoto();">MODIFICA</button><br />
<img id="smallImage" />
</body>
</html>
Any help please?
It runs just fine in both Firefox and Chrome for me. In my limited experience, this.c.pixelData typically comes when your conversion to a CamanInstance was not successfully created.
This can be because of many things, but one that isn't expected is that CamanJS won't let you use the same html identifier (class or id) for more than one object, even if you've swapped them out. So if you're running the two scripts above on the same page, it will cause errors.
Sorry, without being able to reproduce your error, it's hard to help more than that.

Categories

Resources