SLink = [...Array(100).keys()].map(i => `SotiLink[${i}]`)
MCLink = [...Array(100).keys()].map(i => `<MCLink${i}>`)
SotiLink = SLink + MCLink;
console.log(SotiLink)
As a newbie to js I have been trying to improve the current situation, which is as follows:
SotiLink[0] = "<MCLink0>";
SotiLink[1] = "<MCLink1>";
SotiLink[2] = "<MCLink2>";
Now this works fine, it gets the job done.
But I thought something like this would be better:
SotiLink[...Array(100).keys()] = "<MCLink0>", "<MCLink1>", "<MCLink2>", "<MCLink3>", "<MCLink4>", "<MCLink5>", "<MCLink6>", "<MCLink7>", "<MCLink8>", "<MCLink9>", "<MCLink10>", "<MCLink11>", "<MCLink12>", "<MCLink13>", "<MCLink14>", "<MCLink15>", "<MCLink16>", "<MCLink17>", "<MCLink18>", "<MCLink19>", "<MCLink20>", "<MCLink21>", "<MCLink22>", "<MCLink23>", "<MCLink24>", "<MCLink25>", "<MCLink26>", "<MCLink27>", "<MCLink28>", "<MCLink29>", "<MCLink30>", "<MCLink31>", "<MCLink32>", "<MCLink33>", "<MCLink34>", "<MCLink35>", "<MCLink36>", "<MCLink37>", "<MCLink38>", "<MCLink39>", "<MCLink40>", "<MCLink41>", "<MCLink42>", "<MCLink43>", "<MCLink44>", "<MCLink45>", "<MCLink46>", "<MCLink47>", "<MCLink48>", "<MCLink49>", "<MCLink50>", "<MCLink51>", "<MCLink52>", "<MCLink53>", "<MCLink54>", "<MCLink55>", "<MCLink56>", "<MCLink57>", "<MCLink58>", "<MCLink59>", "<MCLink60>", "<MCLink61>", "<MCLink62>", "<MCLink63>", "<MCLink64>", "<MCLink65>", "<MCLink66>", "<MCLink67>", "<MCLink68>", "<MCLink69>", "<MCLink70>", "<MCLink71>", "<MCLink72>", "<MCLink73>", "<MCLink74>", "<MCLink75>", "<MCLink76>", "<MCLink77>", "<MCLink78>", "<MCLink79>", "<MCLink80>", "<MCLink81>", "<MCLink82>", "<MCLink83>", "<MCLink84>", "<MCLink85>", "<MCLink86>", "<MCLink87>", "<MCLink88>", "<MCLink89>", "<MCLink90>", "<MCLink91>", "<MCLink92>", "<MCLink93>", "<MCLink94>", "<MCLink95>", "<MCLink96>", "<MCLink97>", "<MCLink98>", "<MCLink99>";
Where instead of numbering the Sotilink 0-100 it would generate all the numbers.
Ideally I would like the same for MCLink, but so far I had no succes.
I tried to recreate it somewhat in the snippet but I had no succes there either...
Perhaps someone can point me in the correct direction?
Almost there ;)
SotiLink = [...Array(100).keys()].map(i => `<MCLink${i}>`)
console.log(SotiLink)
As a side note, I'm wondering how did you create that snippet in your question. Did you really type all 100 strings? :o
What I thought would be the easiest part of my project has turned into a Herculean effort. All I wanted to do was get data from a JSON file to then display on my website. Prior to using a JSON file, I hard coded some data to test my filter/search functionality, all of which I wrote in JavaScript. The code worked perfectly, so I decided to move the data to a JSON file as I am expecting to have a lot more data in the future and can't have it hardcoded. However, I have been unable to get data from the JSON file successfully. I tried using require('./data.json'), but apparently I can't just use require like that. I then tried importing the file, which only works if I go back to the html and add type="module" to the src tag. This then allows all of the data to display on the webpage, however, the function that allows me to filter by category no longer works. When I click on the buttons, I get no response. I used Inspect to get the console to find the error, and the output is:
Uncaught ReferenceError: filterProject is not defined
The search functionality still works, and I suspect this is because that code isn't inside a function. Thus, I don't know why filterProject is supposedly not defined when the other JS code works. Here is all of my code:
import projects from './data.json' assert { type: "json" };
const path = "http://localhost/static/images/";
//ADDING THE HTML, IGNORE
for(let i of projects){
let card = document.createElement("div");
card.classList.add("card", i["category"], "hide");
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
let imageOne = document.createElement("img");
imageOne.setAttribute("src", path.concat(i["imageOne"]));
imgContainer.appendChild(imageOne);
card.appendChild(imgContainer);
let container = document.createElement("div");
container.classList.add("container");
let name = document.createElement("h3");
name.classList.add("project-name");
name.innerText = i["projectName"].toUpperCase();
container.appendChild(name);
let student = document.createElement("h4");
student.classList.add("student-name");
student.innerText = i["studentName"].toUpperCase() + " mentored by " + i["mentor"].toUpperCase();
container.appendChild(student);
let category = document.createElement("h6");
category.innerText = i["category"].toUpperCase().replace("_", " ");
container.appendChild(category);
card.appendChild(container);
document.getElementById("projects").appendChild(card);
}
//FILTERING (DOESNT WORK)
function filterProject(value){
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
if(value.toUpperCase() == button.innerText.toUpperCase()){
button.classList.add("active");
}else{
button.classList.remove("active");
}
});
let elements = document.querySelectorAll(".card");
elements.forEach((element) => {
if(value == "all"){
element.classList.remove("hide");
}
else{
//having a space messes it up, make it _
if(element.classList.contains(value.replace(" ", "_"))){
element.classList.remove("hide");
}
else{
element.classList.add("hide");
}
}
});
}
//SEARCH (WORKS)
document.getElementById("search").addEventListener
("click", () => {
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".student-name");
let cards = document.querySelectorAll(".card");
elements.forEach((element, index) =>{
if(element.innerText.includes(searchInput.toUpperCase())){
cards[index].classList.remove("hide");
}
else{
cards[index].classList.add("hide");
}
});
});
//INTIAL STATE
window.onload = () =>{
filterProject("all");
};
Here is the HTML just in case as well:
<div class ="wrapper">
<div id="search-container">
<input type="search" id="search-input" placeholder="Search student name here..."/>
<button id = "search">Search</button>
</div>
<div id ="buttons">
<button class = "button-value" onclick="filterProject('all')">All</button>
<button class = "button-value" onclick="filterProject('Creative Project')">Creative Project</button>
<button class = "button-value" onclick="filterProject('Developing Voice')">Developing Voice</button>
<button class = "button-value" onclick="filterProject('Interdisciplinary Fusion')">Interdisciplinary Fusion</button>
<button class = "button-value" onclick="filterProject('Personal Writing')">Personal Writing</button>
<button class = "button-value" onclick="filterProject('Curriculum Designer')">Curriculum Designer</button>
<button class = "button-value" onclick="filterProject('Internship')">Internship</button>
</div>
<div id = projects></div>
</div>
<script type = "module" src = "{{ url_for('static',filename='javascript/script.js') }}"></script>
If it matters, I am using Flask as my web framework. I'm not sure if that has any impact on anything, but it has created some obstacles when I've tried to create a live server to solve this issue. Thanks in advance for any replies!
What you're looking for is how to load json files locally.
One solution is
Start a local server e.g. http://localhost:8080
Then use fetch() to retrieve the json file
For example, if your data.json file was located within the same folder where you have your html file and where you started your server, then your code could be something like
fetch("http://localhost:8080/data.json")
.then((response) => {
return response.json();
})
.then((data) => {
// Add code to process your data
})
This is my first time working with the html template tag. I don't know if I am doing it wrong but the output of the template is only showing the last item in the array. I've tried to loop through it and the foreach method but still only the last item shows. I know I am probably overriding the items as they are stacked on top of each other but I can't seem to figure it out Can someone point me in the right direction?
<div class="products-container">
<template>
<div class="product">
<img class="img">
<h2 class="item-title"></h2>
<h3 class="price"></h3>
</div>
</template>
</div>
const template = document.querySelector('template').content
const copyTemplate = document.importNode(template, true)
let shoppingList = [];
async function getData(data) {
const products = data.items.map(product => {
copyTemplate.querySelector('.item-title').textContent = product.title;
copyTemplate.querySelector('.price').textContent = product.price;
copyTemplate.querySelector('.img').src = product.image;
});
document.querySelector('.products-container').appendChild(copyTemplate);
shoppingList.push(products);
return products
}
I figured it out. I had to put the template and the copytemplate within the map function for it to work.
I am having an issue with a project I'm working on. I am using an API to return an array of platforms a video game is on. The array is returning the correct results, however I am having trouble displaying those values in my HTML. The result is just showing undefined.
// Renders platform information for each game
const renderPlatformInfo = function (platformResult) {
const gamePlatform = [];
for (let i = 0; i <= `${platformResult.length - 1}`; i++) {
let getPlatforms = gamePlatform.push(platformResult[i].name);
}
gamePlatform.forEach(function (platformItem) {
$('.platforms').append(`<li>${platformItem}</li>`)
});
console.log(gamePlatform);
};
// Renders game information for the searched game
const renderGameInfo = function (gameInfoResult) {
return `<div class="js-game-data row">
<h2 class="game-name col-12">${gameInfoResult.name}</h2>
<img src="${gameInfoResult.image.medium_url}" class="game-image col-4" alt="Box art for ${gameInfoResult.name}">
<ul class="platforms col-6">
<h3 class="col-12">Original release date:</h3>${gameInfoResult.original_release_date}
<h3>Platforms:</h3>
${renderPlatformInfo(gameInfoResult.platforms)}
</ul>
<p class="game-description col-6">${gameInfoResult.deck} <br> <br> <span class="game-details col-12"><b>For more details about the game: Click Here</b></span></p>
</div>
`;
}
renderPlatformInfo can't append children to a DOM element that doesn't exist yet. The UL it's trying to select isn't rendered at the time you're trying to append. Additionally, since renderPlatformInfo doesn't return anything, it will always evaluate to undefined inside a template literal. If you return an HTML string inside renderPlatformInfo, your code should work. Try something like:
let str = '';
gamePlatform.forEach(function(platformItem){
str += `<li>${platformItem}</li>`;
});
return str;
Should renderPlatformInfo return something. Are you missing the return there?
I am using app-contacts demo to learn Aurelia, yes I know, it's incomplete as mentioned by #Eisenberg, but then I thought to use EventAggregator to notify the app.js, when I save the contact or create a new contact. Till now everything works fine. I am able to receive the contact object in app.js, but now I would like to update the contact list, which is not working and when I save a contact and update the contacts list in app.js, it gets removed.
Code added in app.js and subscribe method is called in constructor.
subscribe(){
this.ea.subscribe('contact_event', payload => {
console.log(payload);
var instance = JSON.parse(JSON.stringify(payload));
let found = this.contacts.filter(x => x.id == payload.id)[0];
if(found){
let index = this.contacts.indexOf(found);
this.contacts[index] = instance;
}else{
instance.id = this.contacts.length + 1;
this.contacts.push(instance);
}
});
}
No changes made to app.html
<li repeat.for="contact of contacts" class="list-group-item ${contact.id === $parent.selectedId ? 'active' : ''}">
<a href="#" click.delegate="$parent.select(contact)">
<h4 class="list-group-item-heading">${contact.firstName} ${contact.lastName}</h4>
<p class="list-group-item-text">${contact.email}</p>
</a>
</li>
How to update the list?
Update
This worked for me, but not sure what is the right approach
subscribe(){
this.ea.subscribe('contact_event', payload => {
return this.api.getContactList().then(contacts => {
this.contacts = contacts;
});
});
}
Eric L. Anderson does a great job of explaining how this works in his blog post:
Aurelia's Event Aggregator. It's event the same type of code you're trying to do!
Note: it's probably far too late to answer Kishore's question, but I'm putting the link in for others who end up here from a search.