Teton-Coder Teton-Coder -4 years ago 117
Javascript Question

How to unselect a class when clicking on another class with javascript

I have a map of the US with selectable counties that when clicked change their background to red. What I want to happen is when the user clicks on another county it deselects the current county and then selects the new one only. Currently right now when clicking on the county class it changes the class which gives it a background of red, but when you click another county then both are red.

Here is the code where I draw the map and change classes when clicked:

//DRAW MAP
d3.json("js/map.json", function(error, mapData){
if (error) throw error;
//draw counties
edit.map.append("g")
.selectAll("path")
.data(topojson.feature(mapData, mapData.objects.counties).features)
.enter().append("path")
.attr("class", "counties")
.attr("d", edit.path)
.on("click", function(d){
sFips = d.properties.STATEFP;
cFips = d.properties.COUNTYFP;

//display values in text boxes
$("#locationCountySelect").val(cFips);
$("#locationStateSelect").val(sFips);

//change clicked county class name
if (this.className.baseVal == "counties") {
this.className.baseVal = "selectedCounty";
//send new county to db
} else {
this.className.baseVal = "counties";
}
});
});


Again, how can I only have one county selected at a time?

Answer Source

For this purpose I suggest you ditch jQuery in favor of D3. The following two lines in your click listener will do the job:

d3.select(".selectedCounty").attr("class", "counties");
d3.select(this).attr("class", "selectedCounty");

The first statement selects the element having class .selectedCounty and sets the class attribute to counties instead. The second one selects the element clicked upon and set its class to selectedCounty.

It might also be worth considering to keep a reference to the currently selected element in a variable in the outer scope to not having to reselect on every click:

var selectedCounty = d3.select(".selectedCounty");

edit.map.append("g")
// ...
  .on("click", function(d) {
    selectedCounty.attr("class", "counties");
    selectedCounty = d3.select(this).attr("class", "selectedCounty");
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download