How to replace JS variable with JSON file - javascript

I've been working on a website and am new to the website coding scene, my goal is to create a revolving text that goes between words sort of like a splash text on games like Minecraft. I know it's probably best to somehow create a way to connect to a JSON file to my JS one but not quite sure on how to do it. Can someone help?
This is my JS so far and the part of my site that shows the revolving text.
var landingswitchtext = [
'world',
'web',
'video',
'community',
'service',
'home',
'place',
'legacy',
'space',
'server'
];
textSequence(0);
function textSequence(i) {
if (landingswitchtext.length > i) {
setTimeout(function() {
document.getElementById("landing-text-switch").innerHTML = landingswitchtext[i];
textSequence(++i);
}, 2500); // 2.5s (in milliseconds)
} else if (landingswitchtext.length == i) { // Loop
textSequence(0);
}
}
<div class="landing-page">
<h1 class="landing-text">
<center>
building a
<br>
<br>
<span class="magic" id="landing-text-switch">sam</span>
<br>
<br>
for everyone.
</center>
</h1>
</div>

So, you need to have a JSON file and then import it in your script. For that, try the following script:
import * as data from './example.json';
And then use the variable data anywhere you want.

Related

problem when using javascript to display banner, the banner does not display when using javascript?

I am newbie with javascript and here is my problem.
Here is my code
https://codepen.io/nguyencuc2035/pen/XWVXxxK
As you can see in my code, I wrote a javascript to display a banner named toast at a right conner and here is the code
<script>
function toast({
title = '',
message = '',
type = 'info',
duration = 3000
}) {
const main = documet.getElementById('toast');
if (main) {
const toast = documet.createElement('div');
toast.classList.add('toast');
toast.innerHTML = `
<div class="toast__icon">
<i class="fa-solid fa-circle-check"></i>
</div>
<div class="toast__body">
<h3 class="toast__title">Success</h3>
<p class="toast__msg">Import an external stylesheet:</p>
</div>
<div class="toast__close">
<i class="fa-solid fa-xmark"></i>
</div>
`;
main.appendChild(toast);
}
}
toast({
title: 'Success',
message: 'Import an external stylesheet:',
type: 'success',
duration: 3000
})
</script>
Of course in the styles.css I wrote .toast .toast__icon , .toast__body , .toast__close,
But my problem is, when I ran my code, it only display the toast__body and toast__close, not display the toast.
Could you please give me some advice for this problem ? Thank you very much for your time.
I Fidgeted with your code on Codepen, and it seems you've used documet and not document. You're missing an N.
Remember you have to be really careful with your spellings in JavaScript. If it still doesn't work feel free to reply back. Hope this helped.
And if it helps you can use jQuery to just append the banner. It really simplifies the code as well.

Qualtrics using JavaScript library from someone else - chat simulator

I want to build a survey that contains a fake chat. The subject will be participating in the chat.
I found this beautiful library of a chat simulator and tried to use it in one of the questions as following:
upload to my library all the js and css that used through a source link.
add the jquery script to the js option of the question in onLoad() function:
Qualtrics.SurveyEngine.addOnReady(function()
{
jQuery(function($){
var count = 0;
var convForm = $('#chat').convform({eventList:{onInputSubmit: function(convState, ready) {
console.log('input is being submitted...');
//here you send the response to your API, get the results and build the next question
//when ready, call 'ready' callback (passed as the second parameter)
if(convState.current.answer.value==='end') {
convState.current.next = false;
//emulating random response time (100-600ms)
setTimeout(ready, Math.random()*500+100);
} else {
if(Array.isArray(convState.current.answer)) var answer = convState.current.answer.join(', ');
else var answer = convState.current.answer.text;
convState.current.next = convState.newState({
type: 'select',
noAnswer: true,
name: 'dynamic-question-'+count,
questions: ['This question state was built on your previous answer (you answered: '+answer+') and doesnt expect an answer'],
});
convState.current.next.next = convState.newState({
type: 'select',
name: 'dynamic-question-'+count,
questions: ['This question state was built on your previous answer (you answered: '+answer+')'],
answers: [
{text: 'Answer 1', value: '1'},
{text: 'Answer 2', value: '2'},
{text: 'END', value: 'end'}
]
});
//emulating random response time (100-600ms)
setTimeout(ready, Math.random()*500+100);
}
count++;
}}});
});
});
add to the header the <script src="<URL>"> </script> urls of the uploaded files to my library.
made a question through the rich content editor and edit the html:
<section id="demo">
<div class="vertical-align">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 col-xs-offset-0">
<div class="card no-border">
<div id="chat">
<form action="" method="GET" class="hidden">
<select data-conv-question="Hello! This is an example use of the plugin to dynamically generate questions (like using an API). This is the only question that was written on the initial HTML. To end the loop, select END." name="first-question">
<option value="understood">Understood</option>
<option value="okay">Okay, captain!</option>
</select>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
But its not working - just shows a broken chat...
Am I doing it the wrong way?
Is there an easy way to use such library in Qualtrics survey question?
The easiest way to solve this was by using styled tables in the rich content editor.
the dynamic chat was made by inserting the user`s response to the next table.

How Can I use Javascript to loop through an array and change and add extra HTML that outputs some text with those values?

For Example, I am using an API that returns an JSON array of values and I want to output them to the page.
Here is the full code I am working with if anyone wants to try it out to see where I can get it to work.
I have created Some HTML for the layout of the values I want to output when a button is clicked like so:
<p class="txData">
<p id="txHash">Transaction ID: </p><br>
<p id="txTime">Time: </p><br>
<p id="txToken">Token Symbol: </p><br>
<p id="txTo">To: </p><br>
<p id="txFrom">From: </p><br>
<p id="txValue">Amount Transferred: </p><br>
<p>***********************************</p><br>
</p>
I then assign variables for those elements which I want to append to:
let txHash = document.querySelector('#txHash');
let txTime = document.querySelector('#txTime');
let txToken = document.querySelector('#txToken');
let txTo = document.querySelector('#txTo');
let txFrom = document.querySelector('#txFrom');
let txValue = document.querySelector('#txValue');
And I append the retrieved values from the API by doing:
txHash.insertAdjacentHTML('beforeend', jsonFile.result[0].hash);
txTime.insertAdjacentHTML('beforeend', jsonFile.result[0].timeStamp);
txToken.insertAdjacentText('beforeend', jsonFile.result[0].tokenSymbol)
txTo.insertAdjacentHTML('beforeend', jsonFile.result[0].to);
txFrom.insertAdjacentHTML('beforeend', jsonFile.result[0].from);
txValue.insertAdjacentHTML('beforeend', web3.utils.fromWei(jsonFile.result[0].value, 'ether'));
This works to output the values wanted for the first Transaction (index [0]).
How could I create a loop that would basically use the template HTML at the start but then output it for the next 5 elements in the array so that it would be the details for each new trasanction outputted in the same format, but without having to code it 5 times?
I'm new to HTML and Javascript so appreciate any help. Thank you.
First piece of advice, if you don't already know it, you should avoid using static id's in your html template if you plan to use it for displaying a list, because id's must be unique in a single html page.
Second one, you should use a framework to help you displaying your data as a list. If you know famous ones such as Angular or React. You can also use jQuery as someone has advised you.
Here is a little example with VueJS which allows you to define components with html templates. Then, you can use them in a loop with the for directive (please note I'm not a VueJS expert and you may find better solutions) :
<body>
<div id="app">
<div v-for="json in jsonFile">
<data-display v-bind:json="json"></data-display>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
var DataDisplay = {
props: ['json'],
template: '<div class="txData">\
<p>Transaction ID: {{json.hash}}</p>\
<p id="txTime">Time: {{json.timeStamp}}</p>\
<p id="txToken">Token Symbol: {{json.tokenSymbol}}</p>\
<p id="txTo">To: {{json.to}}</p>\
<p id="txFrom">From: {{json.from}}</p>\
<p id="txValue">Amount Transferred: {{json.value}}</p>\
<p>***********************************</p>\
</div>'
};
var vm = new Vue({
el: "#app",
data: {
jsonFile: [
{
hash: 'hash1',
timeStamp: 'timestamp1',
tokenSymbol: 'token1',
to: 'to1',
from: 'from1',
value: 'value1'
}, {
hash: 'hash2',
timeStamp: 'timestamp2',
tokenSymbol: 'token2',
to: 'to2',
from: 'from2',
value: 'value2'
}
]
},
components: {
'data-display': DataDisplay
}
});
</script>
</body>
Documentation used for the example :
https://v2.vuejs.org/v2/guide/components.html
https://v2.vuejs.org/v2/guide/list.html

filepicker.io -- easy implementation

I have a site, btstats.com, that provides the following service:
"It imports a JSON file from 'Bluescan 4.0 Scanner for Android' and generates graphs and stats".
I implemented Dropbox Chooser on my site with this simple and elegant code to provide the functionality, provided by Dropbox:
<script type="text/javascript">
document.getElementById('dropbox-bt').onclick = function()
{
Dropbox.choose
({
linkType: 'direct',
extensions: ['.json'],
multiselect: false,
success: function (files)
{
var dbSelected = "File selected: ";
var filenamePanel = document.getElementById('filenamePanel');
filenamePanel.textContent = dbSelected + files[0].name;
var postLink = files[0].link;
document.getElementById('postLink').value = postLink;
var postName = files[0].name;
document.getElementById('postName').value = postName;
}
});
};
</script>
What I like about the code above is that it is small and provides me the file link and file name.
I'm thinking about implementing filepicker.io, so I can provide to users more cloud storage options.
I couldn't find an easy way to add filepicker.io's window to my site that offers these options. First, I would like to implement it using a button, and I can't find on their documentation an example with getElementById.
Would it be possible for someone to guide me or write a small filepicker.io example based on my Dropbox implementation that provides the file link and file name? I'm not a Javascript expert.
Thanks in advance.
The filepicker code is quite similar:
filepicker.setKey('yourApikey');
document.getElementById('filepickerBtn').onclick = selectFile;
function selectFile(){
filepicker.pick(
// picker options
{
extension: '.json',
},
onSuccessCallback
);
};
function onSuccessCallback(Blob){
document.getElementById('postName').textContent = Blob.filename;
document.getElementById('postlink').textContent = Blob.url;
document.getElementById('results').textContent = JSON.stringify(Blob);
};
Sample html code:
<div class="container">
<h3>Filepicker example</h3>
<p>
<button id="filepickerBtn" class="btn btn-primary">
Select json file
</button>
</p>
<p>Filename: <span id="postName"></span></p>
<p>Filelink: <span id="postlink"></span></p>
<p>Results: <pre id="results">Upload file to see results</pre></p>
</div>
And working example here

creating a dynamic form that builds a multi dimensional array

I am a php developer that is new to angular and javascript in general but finding it really powerful and fast for creating interactive UIs
I want to create a form for a user to create an object called a program, a program has some basic info like title and description and it can have many weeks. I want their to be an 'add week' button that when pressed displays a group of form fields related to weeks, if pushed again it shows another group of form fields to fill in the second weeks information.
edit1: specifically, how I am adding the objects to scope.program with the addWeeks method.
secondly when I console.log the $scope.program it just looks very messy a lot of arrays within objects within objects. it just dosnt look like a clean array of data but maybe thats just because I am not used to javascript and or json? Each week is going to have up to 7 days obviously and each day can have numerous events so it just seems to me like it is going to be quite messy but maybe I should just have faith :p
finally how the addProgram method is creating the json object to be sent to the server
when the form is submitted it should post a json object that looks something like this
program {
title: 'name of programme',
desc: 'description of programme',
weeks: [
{
item1: 'foo',
item2: 'more foo'
},
{
item1: 'foo2',
item2: 'more foo 2'
}
]
]
}
here is a codepen of what I am doing right now but I am not sure it is the best or even an ok way to do it, particularly how I am appending the arrays/objects in teh addWeek method.
there are going to be many more layers to the form and the object it is posting(days, sessions, excersises etc) so I want to get the basics of doing this right before adding all of that.
html
<div ng-app="trainercompare">
<div ng-controller="programsController">
<input type="text" placeholder="Program Title" ng-model="program.title"></br>
<input type="text" placeholder="Program Focus" ng-model="program.focus"></br>
<input type="text" placeholder="Program Description" ng-model="program.desc"></br>
<button ng-click="addWeek()"> add week</button>
<div ng-repeat="week in program.weeks">
<input type="text" placeholder="Name the week" ng-model="week.name">
<input type="text" placeholder="Describe It" ng-model="week.desc">
{{ week.name }}</br>
{{ week.desc }}</br>
</div>
<button ng-click="addProgram()"> add program</button>
</div>
</div>
app.js
var myModule = angular.module("trainercompare", ['ui.bootstrap']);
function programsController($scope, $http) {
$scope.program = {
weeks: [{
}]
};
$scope.addWeek = function() {
$scope.program.weeks.push(
{
}
);
};
function isDefined(x) {
var undefined;
return x !== undefined;
}
$scope.addProgram = function() {
var program = {
title: $scope.program.title,
focus: $scope.program.focus,
desc: $scope.program.desc,
weeks: []
};
angular.forEach($scope.program.weeks, function(week, index){
var weekinfo = {
name: week.name,
desc: week.desc
};
program.weeks.push(weekinfo);
});
$http.post('/programs', program).success(function(data, status) {
if(isDefined(data.errors)) {
console.log(data.errors);
}
if(isDefined(data.success)) {
console.log(data.success);
}
});
};
}
Looks to me like you've got a good grasp on it. The addWeek code looks correct. The extra data you see when you console.log your model is some of Angular's internal stuff to track bindings. When you post that to your server it should be cleaned up by Angular.
Angular has a JSON function that removes all of the hash values and other 'angular' things from your JSON. That's why they start with a $ so it knows to remove them.
This happens automatically when you use $http, it's in the documentation here:
If the data property of the request configuration object contains an object, serialize it into JSON format.
Since Angular will clean up the hashes and things, you don't need to "rebuild" the model when you're posting it... just set data to $scope.program and remove 70% of the code in $scope.addProgram.
To learn more specifically how Angular cleans up the JSON, look at this answer: Quick Way to "Un-Angularize" a JS Object

Categories