I am having trouble with working with AJAX
+ JSON
, every time I try to dynamically write something on my web page, other functionalities just stop working...
Here is my JS
code:
window.onload = function(){
$.ajax({
url: "data/faq.json",
method: "POST",
dataType: "json",
success: function(faq){
ispisFAQ(faq);
},
error: function(error){
console.error(error);
}
});
function ispisFAQ(faq){
let ispis = '<div class="row faqRow">';
faq.forEach(element => {
ispis += `
<button class="${element.class}"> ${element.question} </button>
<div class="content">
<p>
${element.answer}
</p>
</div>`;
});
ispis += '</div>';
document.getElementById("faqContainer").innerHTML = ispis;
}
}
And here is JSON
file :
[
{
"class": "collapsableQuestion",
"question": "1. Do you have a store?",
"answer": "Yes, I do! Currently I have one store on 2424 George Street in Toronto. You can see all the pieces and more there in person!"
},
{
"class": "collapsableQuestion",
"question": "2. Do you ship internationally?",
"answer": "Unfortunately, no. I only ship to Canada, but I'm working on expanding!"
},
{
"class": "collapsableQuestion",
"question": "3. What is your return policy?",
"answer": "Your complete satisfaction is my number one concern.If you are not completely satisfied with your selection, you can return it within 30 days."
},
{
"class": "collapsableQuestion",
"question": "4. What is your jewelry made of?",
"answer": "Quality is very important to me. So I make sure that every piece is made of Gold plated .925 sterling silver. I guarantee that it will last you a long time, with no damage."
},
{
"class": "collapsableQuestion",
"question": "5. Do you clean/repair jewelry?",
"answer": "If it's one of my pieces, sure! Just contact me with details."
},
{
"class": "collapsableQuestion",
"question": "6. Do you make any custom jewerly?",
"answer": "It's not something I do very often, but if you like the style of my jewerly, price and quality - contact me, and I will see what I can do."
}
]
But when I try to run code below, to toggle some content it won't work...
var tog = document.getElementsByClassName("collapsableQuestion");
for (var i = 0; i < tog.length; i++) {
tog[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
Please help me, when I run the same code without AJAX
and JSON
it works fine, what is the problem?