Create a dynamic function with JS [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
I'm working in a project to create a knife in 3 parts and I want to create something like this. I don't really know if it's possible.
//selector
const imgBlade = document.querySelector('.piece__blade');
const imgPart = document.querySelector('.piece__part');
const imgMatter = document.querySelector('.piece__matter');
// here only 3 parts to create the knife but i have alot of more thant that
const shinyBladeImagePath = /img/products/shinyblade.png;
const centralePartImagePath = /img/products/centralePart.png;
const woodCentralePartPath = /img/products/woodCentralePart.png;
class piece {
constructor(name, info, path) {
this.name = name;
this.info = info;
this.path = path;
}
}
let shinyBlade = new piece('SB', 'Shiny Blade', shinyBladeImgPath);
let centralePart = new piece('CP', 'Centrale Part', centralePartImagePath);
let woodCentralePart = new piece('W01', 'Wood Centrale Part', woodCentralePartPath);
class knife {
constructor(blade, part, matter) {
this.blade = blade;
this.part = part;
this.matter = matter;
}
}
let firstKnife = new knife(shinyBlade, centralePart, woodCentralePartPath);
// here I want to create a function to create a dynamic "object" :
function showKnife(event) {
// Here I want to change path with on a click event
imgBlade.src = ;
imgPiece.src = ;
imgMatter.src = ;
}
shinyBladeTitle.addEventListener('click', () => {
showKnife.imgBlade.blade.path;
// here I want to click on a title option and change the imgBlade.src on my function
});
centralePartTitle.addEventListener('click', () => {
showKnife.imgPiece.piece.path;
// here I want to click on a title option and change the imgPiece.src on my function
});
woodTitle.addEventListener('click', () => {
showKnife.imgMatter.matter.path;
// here I want to click on a title option and change the imgPiece.src on my function
});
<div>
<img alt="Blade" src="/img/products/BLANK.png">
<img alt="Part" src="/img/products/BLANK.png">
<img alt="Piece" src="/img/products/BLANK.png">
</div>

Related

Javascript Fetch method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Hello I'm new to JS and fetch api. I'm facing a problem that the following code perfectly works and show the datas from that api when I run that code with node and display in on the console. But when I try to show the datas from the api to the browser with JS DOM , it shows 403 error even though I include the authentication in the headers.
fetch('https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/arrow'
, {
method: 'GET',
mode: 'no-cors',
headers: { app_id: "api_id", app_key: "api_key" },
})
.then((response) => response.json())
.then((data) => {
let noun = document.querySelector("#forNoun")
let verb = document.querySelector("#forVerb")
let nounEg = document.querySelector("#nounEg")
let verbEg = document.querySelector('#verbEg')
let searchbtn = document.getElementById("search")
let searchWord = document.getElementById("word")
let nounDef = document.createElement("p");
let verbDef = document.createElement("p")
let lexicalEntries = data.results[0].lexicalEntries;
let length = lexicalEntries.length
for (let i = 0; i < length; i++) {
console.log(lexicalEntries[i].lexicalCategory.text);
nounVerb.innerHTML = lexicalEntries[i].lexicalCategory.text
let senses = lexicalEntries[i].entries[0].senses;
for (let x = 0; x < senses.length; x++) {
if ("examples" && 'synonyms' in senses[x]) {
// console.log(senses[x].definitions[0])
noun.append(senses[x].definitions[0])
}
else if ('examples' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else if ('synonyms' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
}
}
});
`

getting NaN when asking for video duration [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Can anyone help me understand why console.log(this.getPlayerDuration()) inside of setAttendancePromptTimeLimit() is returning NaN?
// video-player.js
const videoP = document.querySelector('#in-course-player')
class videoPlyer {
constructor(videoElem){
this.vidPlayer = videoElem
}
play = function(cb){
arguments.length ? cb : console.log('play')
}
addListener = (elem, event, cb) => {
elem.addEventListener(event, cb)
}
getPlayerCurrentTime = () => this.vidPlayer.currentTime
getPlayerDuration = () => this.vidPlayer.duration
showVideoDuration = function(cb){
arguments.length ? cb : this.addListener(this.vidPlayer, 'loadedmetadata', () =>
console.log(this.getPlayerDuration()))
}
setAttendancePromptTimeLimit = cb => {
// returns NAN
console.log(this.getPlayerDuration())
}
init = () => {
//returns 16.1
this.showVideoDuration()
//returns NAN
this.setAttendancePromptTimeLimit()
}
}
const coursePlayer = new videoPlyer(videoP)
coursePlayer.init()
[...] If no media data is available, the value NaN is returned. [...]
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/duration

How to optimize and make the code more readable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I barely managed to write this code, though it does its work almost correctly. Nevertheless, I really need your help to make it more readable and meaningful.\
P.S.
OMG I've added tons of comment, but algorithms of the stackoverflow decided that I need to, no, no... I have to add some more useless text here. So Algorithms of the Stackoverflow, is this enough?\
P.P.S.
sorry...
//creating tree of user's properties
//getting users
const request = "https://jsonplaceholder.typicode.com/users";
const xhr = new XMLHttpRequest();
xhr.open("GET", request);
xhr.send();
//when got users render them
xhr.onload = () => {
//getting the root element
const root = document.getElementById("root");
//parsing them into the object
JSON.parse(xhr.response).forEach((user) => {
//=========================================
//creating ul tag for each user <ul>
const ul = document.createElement("ul");
//iterating each users properties
for (const property in user) {
// ====================================
// for each property of a user creating li tag <li>
const listItem = document.createElement("li");
const value = user[property];
// if any property instance of Object,
// then render propery : value
if (!(user[property] instanceof Object)) {
listItem.innerHTML = `${property}: ${value}`;
} else {
//else if property is Object render just name of the property
listItem.innerHTML = `${property}:`;
}
// I know that this "if" statement is peace of unacceptable code
// that's why I'm here to ask you for help
if (user[property] instanceof Object) {
//========================================
//we have 2 Object props, address and company
//here we catch them and iterate each property
if (Object.hasOwnProperty.call(user, property)) {
//=========================================
//creating mini-child ul tag for address and company
const ulmini = document.createElement("ul");
//for each prop of adress or company creating newListItem that is <li> tag
for (const prop in value) {
const newItem = value[prop];
const newListItem = document.createElement("li");
newListItem.innerHTML = `${prop}: ${newItem}`;
//append all <li> tags
ulmini.appendChild(newListItem);
}
listItem.appendChild(ulmini);
}
}
//appending user's all properties
ul.appendChild(listItem);
}
// appending all list of users
root.appendChild(ul);
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>doc</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
The question should actually be posted on codereview.stackoverflow.com.
But to answer, comments are a matter of personal preference or company standards.
Personaly I would do something like this:
Not entirely sure if /** is posible here but otherwise I would use something like this: //***
/**
*
* Insert big description for what the code should do as a whole
*
*/
const request = "https://jsonplaceholder.typicode.com/users";
const xhr = new XMLHttpRequest();
xhr.open("GET", request);
xhr.send();
xhr.onload = () => {
const root = document.getElementById("root");
JSON.parse(xhr.response).forEach((user) => {
const ul = document.createElement("ul");
for (const property in user) {
const listItem = document.createElement("li");
const value = user[property];
/**
* Subhead description for code underneath
*/
if (!(user[property] instanceof Object)) {
listItem.innerHTML = `${property}: ${value}`;
} else {
listItem.innerHTML = `${property}:`;
}
/**
* Subhead description for code underneath
*/
if (user[property] instanceof Object) {
if (Object.hasOwnProperty.call(user, property)) {
const ulmini = document.createElement("ul");
for (const prop in value) {
const newItem = value[prop];
const newListItem = document.createElement("li");
newListItem.innerHTML = `${prop}: ${newItem}`;
ulmini.appendChild(newListItem);
}
listItem.appendChild(ulmini);
}
}
ul.appendChild(listItem);
}
root.appendChild(ul);
});
};
In terms of the code itself, it is already pretty clean/short so I wouldn't recommend changing it if it works.

Click event on array with multiple elements but individually [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to cycle through an array with a for...of loop but need each element in the array to be a separate click event (not grabbing all of them) - without using jQuery.
Here's what I have so far ...
const dataScrollTo = document.querySelectorAll('[data-scroll-to]');
let ss = 1000;
let o = 0;
const scrollMe = function scrollMe() {
for (const el of dataScrollTo) {
const trigger = el.getAttribute('data-scroll-to');
const target = document.getElementById(trigger);
const dsoGet = el.getAttribute('data-scroll-offset');
const dssGet = el.getAttribute('data-scroll-speed');
target.scrollIntoView({
behavior: 'smooth'
});
if (dsoGet) {
o = dsoGet;
}
if (dssGet) {
ss = dssGet;
}
}
};
document.addEventListener('click', scrollMe);
And the HTML (there are a few navigation divs similar to this one).
<div>
<a class="icon-link" data-scroll-to="research" data-scroll-offset="60">
</a>
</div>
You should add the event listener to each element, not document. The listener can use this to tell which element was clicked on.
function scrollMe() {
const el = this;
const trigger = el.getAttribute('data-scroll-to');
const target = document.getElementById(trigger);
const dsoGet = el.getAttribute('data-scroll-offset');
const dssGet = el.getAttribute('data-scroll-speed');
target.scrollIntoView({
behavior: 'smooth'
});
if (dsoGet) {
o = dsoGet;
}
if (dssGet) {
ss = dssGet;
}
}
dataScrollTo.forEach(el => el.addEventListener("click", scrollMe));

Go to nextURL on local server

I need to go to the next URL after a correct answer on a quiz. I have an assignment where I'm creating a Quiz game with questions from a server at the university. When the person is correct the game gets the next question on the server with a XMLHttpRequest.
How can I somehow us a 'nextURL' here or is there no such term?
function Question () {
let quizQuestion = new window.XMLHttpRequest()
quizQuestion.open('GET', 'http://vhost3.lnu.se:20080/question/1')
quizQuestion.onload = function () {
let ourData = JSON.parse(quizQuestion.responseText)
let questionDiv = document.querySelector('#question')
questionDiv.innerText = ourData.question
}
quizQuestion.send()
answer()
}
function answer () {
let quizQuestion = new window.XMLHttpRequest()
let answerDiv = document.querySelector('#answer')
let button = document.createElement('button')
button.type = 'button'
button.setAttribute('id', 'send')
button.innerText = 'Answer'
answerDiv.appendChild(button)
button.addEventListener('click', function () {
quizQuestion.open('POST', 'http://vhost3.lnu.se:20080/answer/1')
quizQuestion.setRequestHeader('Content-type', 'application/json')
quizQuestion.send(JSON.stringify({answer: inputText.value}))
quizQuestion.onreadystatechange = function () {
console.log(quizQuestion.response)
let ourAnswer = JSON.parse(quizQuestion.responseText)
let answerDiv = document.querySelector('#answer')
answerDiv.innerText = ourAnswer.message
}
})
}
So if the value in ({answer: inputText.value}) is correct I want to go to the next question, which in this case is in quizQuestion.open('GET', 'http://vhost3.lnu.se:20080/question/21')
Based on what you've written, it looks like "next URL" at any given moment would be next in a list that you've been given, and it's up to you to figure out how to retrieve the appropriate one after a correct answer.
We'll assume the question numbers in your assignment are non-sequential (moving from question 1 to question 21 in your example), and that no questions repeat. Is there a list of the questions in the order you need on the server? If the list is in an array, can you access it based on the index of the current question?
If not, assuming you already know the list of questions in the desired order, you can do this in your own code. Suppose you put your question numbers into an array, and store the current question number, like so:
let questionNums = [1,21,14,9,6,23]
let currQuestionNum = questionNums[0]
This lets you concatenate the desired question number onto your base URL as
'http://vhost3.lnu.se:20080/question/' + currQuestionNum.toString().
Then, when you've checked if the answer is correct, you can move to the next question in the array:
if (questionNums.indexOf(currQuestionNum)+1 != questionNums.length){
currQuestionNum = questionNums[questionNums.indexOf(currQuestionNum)+1]
}
else{
//end the quiz
}
To use this with the concatenation example above, you'll need to modify your Question and answer functions to accept question numbers as parameters:
function Question (questionNum) {
let quizQuestion = new window.XMLHttpRequest()
quizQuestion.open('GET', 'http://vhost3.lnu.se:20080/question/'+questionNum)
quizQuestion.onload = function () {
let ourData = JSON.parse(quizQuestion.responseText)
let questionDiv = document.querySelector('#question')
questionDiv.innerText = ourData.question
}
quizQuestion.send()
answer(questionNum)
}
function answer (questionNum) {
let quizQuestion = new window.XMLHttpRequest()
let answerDiv = document.querySelector('#answer')
//Local answerNum variable
let answerNum = questionNum
let button = document.createElement('button')
button.type = 'button'
button.setAttribute('id', 'send')
button.innerText = 'Answer'
answerDiv.appendChild(button)
button.addEventListener('click', function () {
quizQuestion.open('POST', 'http://vhost3.lnu.se:20080/answer/'+answerNum)
quizQuestion.setRequestHeader('Content-type', 'application/json')
quizQuestion.send(JSON.stringify({answer: inputText.value}))
quizQuestion.onreadystatechange = function () {
console.log(quizQuestion.response)
let ourAnswer = JSON.parse(quizQuestion.responseText)
let answerDiv = document.querySelector('#answer')
answerDiv.innerText = ourAnswer.message
}
})
}
Note the local answerNum variable - this is added so that, if quesitonNum changes before the anonymous function is called on a click event, the value won't be affected.

Categories

Resources