I’m adding a dropdown element to the page dynamically through javascript. I want this dropdown to be able to change the properties displayed on a map, so I’m attempting to add the element after the map loads. The issue I’m having is that the dropdown element is rendered multiple times on the page, and additional dropdown elements are added every time I re-size the page?
Here’s some pseudo-code, apologies: I’m not able to post a replicable example at the moment because this is embedded in a r2d3 framework (d3.js library in R) and that would get overly complicated.
Any thoughts as to why this is duplicating the dropdown?
//set default property for map so it knows which field to use for the map fill color
var dropdown_val = 'ODpc'
//function that initially draws the map
function loadMap(dropdown_val) {
map2.on('load', function () {
// Add source and layers, etc...
// Create and inside the load function instead.
addElement();
});
}
loadMap(dropdown_val)
//this will be used to add sidebar to the page
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
function addElement() {
// create a sidebar to hold dropdown
const sidebar = document.createElement("div");
sidebar.className = "sidebar";
sidebar.id = "sidebar";
//For the dropdown: Create array of options to be added
var array = ["2014-2022", "2022","2021","2020","2019", "2018", "2017", "2016", "2015", "2014"];
var val_array = ["ODpc", "ODpc2022","ODpc2021","ODpc2020","ODpc2019", "ODpc2018", "ODpc2017", "ODpc2016", "ODpc2015", "ODpc2014"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "mySelect";
selectList.className = "mySelect";
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = val_array[i];
option.text = array[i];
selectList.appendChild(option);
}
//make legend etc.. etc...
// Connect the event listener
selectList.addEventListener('change', onChange);
// add the newly created element and its content into the DOM
// Get a reference to the parent node
const parentDiv = document.getElementById("map_choropleth_state").parentNode;
const mapDiv = document.getElementById("map_choropleth_state");
//add the sidebar, which will hold the dropdown
insertAfter(sidebar, mapDiv);
//add the dropdown
sidebar.appendChild(selectList);
};
function onChange(event) {
const dropdown_val = event.target.value;
// Update the layers depending on the value
}
Picture here: