I use MathJax to display formulas and more things in math. Like square root, limits, logarithm etc..
I have array of objects. Every object has 2 values. Question, Answer
/Objects/Matematika1.js
export const examples = [
{
question: "\\(ax^2 + bx +c = 0\\)",
answer: "(answer for 1)",
},
How app works:
In the menu i click something for example Math (Matematika1). Menu is standart <a href> with onClick function and ID. The function gets the ID and save it in localStorage
Menu Item
Matematika#1
I have a localStorage array but i need only ID as string.
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
And then i need the value of selectedPage insert to import path. Object has same name as ID in menu item
//localStorage array to string variable
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
//import { examples } from "./Objects/Matematika1.js";
//importing the array from /object/"selectedPage"
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
//console.log(array);
function toggle(i) {
const div = document.querySelector(`#result_${i}`);
if (div.style.display !== "none") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
const container = document.querySelector("#examples-container");
examples.forEach((ex, i) => {
const card = document.createElement("div");
card.classList.add("card");
const example = document.createElement("div");
example.classList.add("example");
example.innerHTML = ex.question;
card.appendChild(example);
const button = document.createElement("button");
button.classList.add("toggle");
button.innerHTML = "Toggle";
button.addEventListener("click", () => toggle(i)); // Here is the event listener
card.appendChild(button);
const result = document.createElement("div");
result.id = "result_" + i;
result.style.display = "none";
result.classList.add("result");
result.innerHTML = ex.answer;
card.appendChild(result);
container.appendChild(card);
});
})
.catch((err) => {
console.log(err);
});
My issue is when i comment these lines and set static import path. MathJax render is working very well. But i need set import path dynamicly and in this case MathJax is not working.
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
})
.catch((err) => {
console.log(err);
});
To be honest i have no idea what's wrong. The import("..").then().catch() i copied from this forum. In DOM i can't see any MathJax class so it look's JS don't have access to MathJax Library?
<div id="examples-container"></div> and also MathJax imported in index.html
Related
I have a list of expenses, I want to create a html code to iterate over all the expenses and show their name. I am not working with the DOM, I literally want to save the html code in a variable, so I can generate a pdf file with it.
This is what I tried:
lets say I have this array
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
const testHtml = () => {
for(let i of spents) {
const title = `<h1>${i.expenseName}</h1>`
}
}
testHtml()
This is the result I want, something like:
htmlResult = "<h1>${i.expenseName}</h1> <h1>${i.expenseName}</h1>"
by the way, This is for a react native app.
I think this will work for you.
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
const testHtml = () => {
let title = '';
for(let i of spents) {
title += `<h1>${i.expenseName}</h1>`
}
return title;
}
testHtml()
You could use Array.prototype.reduce().
const spents = [{
expenseName: "Pizza"
}, {
expenseName: "Home"
}];
const result = spents.reduce((prev, curr, index) => index === 0 ? curr.expenseName : `<h1>${prev}</h1> <h1>${curr.expenseName}</h1>`, '');
document.body.append(result);
I have created a card structure based on results array fetched from API as:
results holds the list of fetched data
resultsDiv is an empty div to append all cards in it
created cards as :
results.forEach((pred, idx) => {
const card = document.createElement('div')
card.classList.add('card');
card.id = idx;
const image = document.createElement('img');
image.src = pred["image_path"]
image.classList.add('image-style')
card.append(image)
const info = document.createElement('h4')
info.innerText = 'Tenant ID: ' + pred["tenant_id"]
card.append(info)
resultsDiv.append(card)
const ol = document.createElement('ol')
pred['prediction'].forEach(p => {
const li = document.createElement('li')
const checkbox = document.createElement("INPUT");
checkbox.setAttribute("type", "checkbox");
li.innerText = p
li.appendChild(checkbox)
ol.appendChild(li)
})
card.append(ol)
const btn = document.createElement('button')
btn.innerText = 'Verify'
btn.classList.add('verify-btn')
const textarea = document.createElement('textarea')
textarea.placeholder = 'comments...'
card.append(btn)
card.append(textarea)
})
Now I want to get all the data that are selected on respective card on clicking its own button (each button i have added an event listener)
currently I am getting the values using closest this works but i think its not the appropriate way :
btn.addEventListener('click', () => {
const cardDiv = btn.closest('div');
const allElems = cardDiv.childNodes;
const imagePath = allElems[0].src; // image src
const comments = allElems[4].value; //
})
May I know any efficient way of getting the values as above , any guiding links or a solution would be much helpful
TIA
In the image below is the screenshot of my wix editor where i'm trying to create a basic color assigner which is supposed to assign the big box the color of the button that is clicked by someone.
enter image description here
Please review and see why the code i am using is not working.
Here is the code;
$w.onReady(function () {
// Selectors for all the Container boxes
const bigBox = $w('#box0');
const boxColor = bigBox.style.backgroundColor;
const firstButton = $w('#button1');
const firstcolor = firstButton.style.backgroundColor;
const secondButton = $w('#button2');
const secondColor = secondButton.style.backgroundColor;
const thirdButton = $w('#button3');
const thirdColor = thirdButton.style.backgroundColor;
const fourthButton = $w('#button4');
const fourthColor = fourthButton.style.backgroundColor;
firstButton.onClick(event => {
boxColor = firstcolor;
});
secondButton.onClick(event => {
boxColor = secondColor;
})
thirdButton.onClick(event => {
boxColor = thirdColor;
})
fourthButton.onClick(event => {
boxColor = fourthColor;
})
});
You can't assign the color to the box the way you are trying to do it. What you are currently doing is storing the initial value of the box in a variable and then just changing the value of that variable. When you change the variable, it will not do anything to the box. Instead, you need to actually change the value of the box's backgroundColor.
So the bottom section of your code should look something like this:
firstButton.onClick(event => {
bigBox.style.backgroundColor = firstcolor;
});
secondButton.onClick(event => {
bigBox.style.backgroundColor = secondColor;
})
thirdButton.onClick(event => {
bigBox.style.backgroundColor = thirdColor;
})
fourthButton.onClick(event => {
bigBox.style.backgroundColor = fourthColor;
})
And you can get rid of this line on the top:
const boxColor = bigBox.style.backgroundColor;
I am new to JavaScript. I have a small code that creates list from input and then adds it to an array. I am able to remove one item from the DOM when the item is clicked, but I couldn't remove it from the array.
I tried to use array.splice(item, 1)
lists.addEventListener("click", function (e) {
e.target.closest("li").remove();
userInputArr.splice(item, 1);});
But it removes the entire array sometime, and sometime removes the last item. when I console log the code, it looks like I clicked 3 or 4 times on the list even though I just clicked once. I have no idea what's wrong. this is the entire code:
const lists = document.querySelector(".lists");
const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");
const item = document.querySelectorAll(".list");
userInputArr = [];
function addNote() {
if (userInput.value < 1) {
return;
}
lists.insertAdjacentHTML(
"afterbegin",
`<li class='list'>${userInput.value}</li>`
);
userInputArr.push(lists);
lists.addEventListener("click", function (e) {
e.target.closest("li").remove();
userInputArr.splice(item, 1);
});
userInput.value = "";
}
addBtn.addEventListener("click", function () {
addNote();
});
Code is totally meaningless
1)
userInputArr.push(lists)
why you push the same element all the time? As lists refers to the first and the only element with class 'lists'?
2)
userInputArr.splice(item, 1)
please watch carefully what splice does? The first argument is number, but you pass a collection of elements with class 'list'. But i camn not even suggest which element should be removed as it contains the same element as i mentioned in first point
3) You do not need this array at all
So right approach is something like this
const lists = document.querySelector(".lists");
// just once create listener, no need to do it each time
lists.addEventListener("click", function (e) {
// if you want to remove clicked item then
if (e.target.tagName === 'LI') e.target.remove();
// but if you want to remove the first one then uncomment line
// if (this.children[0]) this.children[0].remove()
});
const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");
///////////////////////////////////////////////////
// item is meaninglee here, so delete this line
// const item = document.querySelectorAll(".list");
//////////////////////
// array is useless too, delete this line
// userInputArr = [];
function addNote() {
// check if it is number
if (isNaN(userInput.value) || Number(userInput.value < 1)) {
return;
}
lists.insertAdjacentHTML(
"afterbegin",
`<li class='list'>${userInput.value}</li>`
);
userInput.value = "";
}
addBtn.addEventListener("click", function () {
addNote();
});
const items = (() => {
const _items = {};
let key = 0;
return {
put(value) {
_items[key++] = value;
console.log("Added", this.all());
return key - 1;
},
remove(key) {
delete _items[key++];
console.log("Removed", this.all());
},
all(asArray = true) {
return asArray ? Object.values(_items) : { ..._items
};
}
}
})();
const inputEl = document.querySelector(".input");
const itemsEl = document.querySelector(".items");
const addBtn = document.querySelector(".btn-add");
addBtn.addEventListener("click", () => {
const value = inputEl.value.trim();
if (!value.length) return;
const key = items.put(value);
const li = document.createElement("li");
li.textContent = value;
li.dataset.key = key;
itemsEl.append(li);
inputEl.value = "";
});
itemsEl.addEventListener("click", (e) => {
const li = e.target.closest("li");
items.remove(li.dataset.key);
li.remove();
});
<input type="text" class="input">
<button class="btn-add">Add</button>
<ul class="items"></ul>
Run code & View in full screen.
use shift() userInputArr.shift()
you are also getting double clicks because your addNote() function contains an event listener lists.addEventListener and it's executed by another event listner addBtn.addEventListener you should probably move
lists.addEventListener out of the addNote function
So I have this code:-
const extendCSS = (el1, el2) =>{
Array.prototype.slice.call(document.querySelector(el1).attributes).forEach(function(item) {
el2.setAttribute(item.name, item.value);
});
}
const build = (elementType) => tag => {
const query = document.querySelectorAll(tag);
query.forEach(ptag => {
const shadow = ptag.attachShadow({
mode: 'open'
});
const element = document.createElement(elementType);
element.innerHTML = ptag.innerHTML;
extendCSS(tag, element);
element.setAttribute('id', tag);
shadow.host.parentNode.replaceChild(element, shadow.host);
});
};
const h1 = build('h1');
const textarea = build('textarea');
textarea("text-editor");
h1("text-value");
const texteditor = document.querySelector('#text-editor');
const textvalue = document.querySelector('#text-value');
texteditor.addEventListener('keydown', ()=>{
textvalue.innerHTML = texteditor.value;
});
<text-editor></text-editor>
<text-value></text-value>
This build() does one thing:- it selects the custom element, changes its tag type and assign a id of name of the custom tag and replaces it with the desired thing. It is working fine here. but if I code all the thing after the build function in a external .js file and then bind it to the html and run it, but it won't work. How can I resolve this? This is a very important for now.
Help and answers appreciated. Thanks in advance.