I have an SVG with large circles connected to small squares. The circles have classes A, B, C, etc. and the squares have corresponding classes, though some have more than one. I need a way to click on a circle and add a class to all elements that contain that class. Conversely, I also need to be able to click on a square, and have it add a class to all circles that match the array of classes. I'm sure this is easy, though I'm afraid I'm not experienced enough to have figured it out. Here's what I have so far.
// Click on circle to highlight boxes and connected lines
$('body').on('click','circle, ellipse, .program',function() {
var className = $(this).attr('class');
var classArr = className.split(/\s+/);
$("svg circle, svg path, svg ellipse").each(function() {
var indvClass = $(this).attr('class');
if ($.inArray(indvClass, classArr) !== -1 || $(this).hasClass('active')) {
$(this).toggleClass('active');
$(this).closest('.line').toggleClass('active');
}
})
});
EDIT --
Is it possible that it's firing before the SVG loads? I have updated my code, but it's not working in production.
$( '.mapsvg-wrap' ).find( 'circle, ellipse, path' ).click( function() {
var isActive = $( this ).hasClass( 'active' );
var classList = $( this ).attr( 'class' ).split( /\s+/ );
$( '.active' ).removeClass( 'active' );
if ( ! isActive ) {
$.each( classList, function( index, className ) {
if ( 'active' != className ) {
$( '.' + className ).addClass( 'active' );
} else {
$( '.active' ).removeClass( 'active' );
}
} );
}
});
It is not clear to me exactly what you would like to achieve. But here I have an event listener on <svg>. 1) When clicked all "active" class names are removed. 2) for each of the class names for the clicked element, update the class list of the elements with that class name with "active".
document.addEventListener('DOMContentLoaded', e => {
// eventlistener for click
document.querySelector('svg').addEventListener('click', e => {
// remove all class names "active"
document.querySelectorAll(`svg .active`).forEach(elm => elm.classList.remove('active'));
// for each of the class names for the clicked element
e.target.classList.forEach(cl => {
// add "active" to all elements with that class name
document.querySelectorAll(`svg .${cl}`).forEach(elm => elm.classList.add('active'));
});
});
});
.active {
fill: red;
}
<svg viewBox="0 0 10 10" width="200" xmlns="http://www.w3.org/2000/svg">
<ellipse class="a" cx="2" cy="5" rx="2" ry="4"/>
<ellipse class="b" cx="5" cy="5" rx="2" ry="4"/>
<path class="a" d="M 0 0 L 0 1 L 1 1 L 1 0 Z"/>
<path transform="translate(2 0)" class="a b" d="M 0 0 L 0 1 L 1 1 L 1 0 Z"/>
<path transform="translate(4 0)" class="b c" d="M 0 0 L 0 1 L 1 1 L 1 0 Z"/>
</svg>