I got this problem where my JS-functions won't work/run after i rebuild my HTML page with some new values from my XML-file. To not make this post too long i gathered the HTML/CSS in jsfiddle: http://jsfiddle.net/qua1ity/g91xpfhx/ (I'ts not fully functional since i don't know how to add xml/ajax stuff to jsfiddle)
Basically, there is an image and a checkbox, when the checkbox is checked then the image gets the class "markedImg" which have a opacity value of 1. This doesn't work when i try to rebuild the html with values from an XML file.
I do the request like this:
function doRequest(target) {
if (XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return false;
}
request.open("GET", target, true);
request.send(null);
request.onreadystatechange = function () {
if ((request.readyState === 4) && (request.status === 200)) {
createHTML(request.responseXML);
}
};
}
Sending "target" parameter from an addeventlistener
categoryMenu.addEventListener("change", function () {
if (categoryMenu.value === "Flower") {
doRequest("categories/imgcat0.xml");
}
if (categoryMenu.value === "Buttefly") {
doRequest("categories/imgcat1.xml");
}
});
And then i run the function "createHTML", which rebuilds the html using the values from XML files
function createHTML (XMLcode) {
var imgURL = XMLcode.getElementsByTagName("image");
var title = XMLcode.querySelector("title");
var html = "";
imgForm.innerHTML = "";
html += '<h3>' + title.firstChild.data + '</h3>';
for (var i = 0; i < imgURL.length; i++) {
html += '<div class="outerBox">';
html += '<label><input type="checkbox" align="middle"><img src="' + imgURL[i].children[0].childNodes[0].nodeValue + '" alt="img 1" class="unmarkedImg"></label>';
html += '<div class="innerBox">';
html += '</div>';
html += '</div>';
}
imgForm.innerHTML = html;
}
And so far everything works, but when i add the function to add the "markedImg" class, it doesn't run on the newly created HTML elements. Nothing happens with this function basically. The function itself works, which you can see in the jsfiddle example, but it's after you change the category and the "doRequest" functions runs that it doesn't work.
checks.forEach(function (checkbox, index) {
checkbox.onchange = function () {
if (this.checked) {
unmarkedImg[index].classList.add("markedImg");
} else {
unmarkedImg[index].classList.remove("markedImg");
}
};
});
The XML is very simple, just a title and source to the images:
<imagecategory>
<title>Butterfly</title>
<image>
<url>http://i.imgur.com/LY1Mq8k.jpg</url>
</image>
</imagecategory>
Sorry if the post got a bit long.. Hopefully this makes sense to someone. Thanks!