How can I add a active class to a svg path?

Viewed 222

I want to add a active class so that whenever I click on a path it will be active until I click the other one. The minimal way of doing this would be appreciable. I already made this svg clickable using jquery. Please see the demo img. Here is my jquery code-

$(document).ready(function () {
$('#mySVG').load("bd-map.html", function () {

    $("#bd-map").click(function (evt) {
        switch (evt.target.id) {
            case "panchagarh":
                $('#info').load('info.html #panchagarh')     //loading data from info.html
                break;
            case "bandarban":
                $('#info').load('info.html #bandarban')     //loading data from info.html
                break;
            case "comilla":
                $('#info').load('info.html #comilla')
                break;
            case "sylhet":
                $('#info').load('info.html #sylhet')
                break;
        }
    });
});

})

1 Answers

This should do it, assuming the element you want the class added to is an SVG that lives inside the #bd-map container. The trick is that you're either clicking on the path or text element, so you have to sniff for tagName and then react accordingly. The path to the path from the text element is $(evt.target).parent().prev('path') (keeping things in jQuery)

$("#bd-map").click(function(evt) {
  $("#bd-map").find('path').removeClass('active');
  let targ = evt.target.tagName === 'path' ? $(evt.target) : $(evt.target).parent().prev('path');
  console.log(targ.attr('id'))
  targ.addClass('active')
  switch (targ.attr('id')) {
    case "panchagarh":
      $('#info').load('info.html #panchagarh') //loading data from info.html
      break;
    case "bandarban":
      $('#info').load('info.html #bandarban') //loading data from info.html
      break;
    case "comilla":
      $('#info').load('info.html #comilla')
      break;
    case "sylhet":
      $('#info').load('info.html #sylhet')
      break;
  }
});
Related