How do I trigger a change event using a custom HTMLElement?
I have an eventlistener registered in an section
HTML tag that has embedded various dropdowns:
function dropdownChange(e) {
window.console.log("The event is detected");
if (e.target.tagName === "SELECT")
window.console.log("The event target is a dropdown"); // Some jobs
else
window.console.log("The event target is NOT a dropdown"); // Some jobs
}
document.getElementById("filterSection").addEventListener("change", dropdownChange);
It works great.
What I want to do is trigger a change event when my page is loaded. As far as I understand the Mozilla documentation I have to follow when my DOM is ready for the next action:
document.getElementById("periode").dispatchEvent(new Event("change"));
But the event is not a trigger (I am not getting any traces in my console). I thought propagating events would do the job ...
If I execute:
document.getElementById("filterSection").dispatchEvent(new Event("change"));
The event works well, but the target is not very good.
What am I doing wrong?
Dropdown HTML:
<section id="filterSection">
<label>Période</label>
<select name="periode" id="periode">
<option value="2014-08">2014 Août</option>
<option value="2014-07">2014 Juillet</option>
<option value="2014-06">2014 Juin</option>
<option value="2014-05">2014 Mai</option>
<option value="2014-04">2014 Avril</option>
<option value="2014-03">2014 Mars</option>
<option value="2014-02">2014 Février</option>
<option value="2014-01">2014 Janvier</option>
<option value="2013-12">2013 Décembre</option>
<option value="2013-11">2013 Novembre</option>
<option value="2013-10">2013 Octobre</option>
<option value="2013-09">2013 Septembre</option>
<option value="2013-08">2013 Août</option>
<option value="2013-07">2013 Juillet</option>
<option value="2013-06">2013 Juin</option>
</select>
<!-- Other dropdowns...-->
</section>
My main browser target is Firefox.17
source to share
I would suggest using document.querySelector
getById instead as it is more reliable.
So change your event additions / dispatching below.
document.querySelector("#periode").addEventListener("change", dropdownChange);
document.querySelector("#periode").dispatchEvent(new Event("change"));
UPDATE: to have a parent and let all children have the same event by following the code:
function dropdownChange(e) {
window.console.log("The event is detected");
if (e.target.tagName === "SELECT") window.console.log("The event target is a dropdown");
else window.console.log("The event target is NOT a dropdown");
}
//shiv, add a forEach to nodeList prototype to use forEach method on querySelectorAll lsit.
NodeList.prototype.forEach = Array.prototype.forEach;
var parent = document.querySelectorAll("#filter select");
parent.forEach(function(e){
e.addEventListener("change", dropdownChange);
});
document.querySelector("#filter select").dispatchEvent(new Event("change"));
source to share