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");
});
CodePudding user response:
If you are using inline svg's like you say then you can just toggle the id referenced in the svg.
$(".Icon use").on("click", function() {
if ($(this).attr("href") === "#Icon-On") {
$(this).attr("href", "#Icon-Off");
} else {
$(this).attr("href", "#Icon-On");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 0; width: 0; position: absolute; visibility: hidden;">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol id="Icon-On" viewBox="0 0 1024 1024">
<path d="M512 32l-480 480h288v512h384v-512h288z" />
</symbol>
<symbol id="Icon-Off" viewBox="0 0 1024 1024">
<path d="M864 128l-480 480-224-224-160 160 384 384 640-640z" />
</symbol>
</svg>
</div>
<svg ><use href="#Icon-Off" /></svg>
<svg ><use href="#Icon-Off" /></svg>
CodePudding user response:
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/