Issue
I'm trying to toggle an SVG button from one state to the other. They are two separate SVGs contained in a larger SVG.
For reference I've attached these images here:
So far I have come up with this where onclick I change the ID value from display on or off as shown below. I'm sure there is a much cleaner way to do this using jQuery?
HTML SVG Code was to long so I've added to pastebin
JS Code
$( "#off-btn-nav-01-category" ).on( "click", function() {
$("#off-btn-nav-01-category").css("display", "none");
$("#on-btn-nav-01-category").css("display", "block");
});
$( "#on-btn-nav-01-category" ).on( "click", function() {
$("#on-btn-nav-01-category").css("display", "none");
$("#off-btn-nav-01-category").css("display", "block");
});
Solution
You can use the startswith operator for jQuery selector, mine the number and type from the id and apply it in your further selectors:
$('[id^="off-btn-nav"], [id^="on-btn-nav"]').click(function() {
let idParts = this.id.split("-");
let number = idParts[idParts.length - 2];
if (idParts[0] === "on") {
$(`#on-btn-nav-${number}-${idParts[idParts.length - 1]}`).hide();
$(`#off-btn-nav-${number}-${idParts[idParts.length - 1]}`).show();
} else {
$(`#on-btn-nav-${number}-${idParts[idParts.length - 1]}`).show();
$(`#off-btn-nav-${number}-${idParts[idParts.length - 1]}`).hide();
}
});
Excuse me for not creating a snippet, stackoverflow.com said it would be too long.
JSFiddle: https://jsfiddle.net/tygkjLvf/
Answered By - Lajos Arpad


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.