To replace basic SVG icons upon clicking with the use of HTML, CSS, and jQuery - here's how!

I have a simple question about inline SVG icons and how to handle them in HTML, CSS, and jQuery. Despite reading numerous resources, I still struggle with implementing the functionality where clicking on one icon changes it to another.

My objective: To toggle between two different icons (e.g., + icon to - icon) when clicked.

What I've done so far: I downloaded two SVG icons from Noun Project and added the code for the + icon in my HTML markup. Here's a glimpse of where I'm at currently.

See current progress here

<div class="border"></div>
                <div class="clickableList">
                    <span class="types">Swap icons</span>
                    <svg width="20px" height="20px" viewBox="0 0 74 74" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                        <title>noun_1776266_cc</title>
                        <desc>Created with Sketch.</desc>
                        <defs></defs>
                        <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                            <g id="noun_1776266_cc_2" transform="translate(0.000000, -1.000000)" fill="#000000" fill-rule="nonzero">
                                <g id="Group" transform="translate(0.000000, 0.637820)">
                                    <polygon id="Shape" points="33 0.36218 33 33.36218 0 33.36218 0 41.3622 33 41.3622 33 74.3622 41 74.3622 41 41.3622 74 41.3622 74 33.36218 41 33.36218 41 0.36218 33 0.36218"></polygon>
                                </g>
                            </g>
                        </g>
                    </svg>
                </div>

.types {
  font-size: 20px;
  font-family: arial;
}

$('.clickableList').click(function() {
event.preventDefault();

I'm now struggling with integrating the second icon into my HTML so that when the first icon is clicked, it morphs into this new icon. Below is the markup for the second icon that's causing me some confusion.

<!-- second SVG-->
<svg width="20px" height="20px" viewBox="0 0 74 74" version="1.1" 
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>noun_line_1776294</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
    <g id="noun_line_1776294" transform="translate(-6.000000, -31.000000)">
        <g id="Group" transform="translate(0.000000, 0.637820)">
            <polygon id="Shape" fill="#000000" fill-rule="nonzero" points="6 30.36218 6 38.36218 68 38.36218 68 30.36218"></polygon>
            <rect id="Rectangle" x="0" y="0" width="74" height="69"></rect>
        </g>
    </g>
</g>
</svg>

Answer №1

At its core, jQuery is simply a library that simplifies the use of Javascript, making it easier to implement new features effortlessly. Due to its widespread popularity, many mistakenly equate jQuery with Javascript itself. While coding in Javascript, utilizing jQuery can significantly streamline tasks such as modifying HTML elements.

Instead of manually embedding SVG images, I suggest utilizing Font Awesome icons for improved ease of management. However, if you specifically seek a way to convert a plus sign to a minus sign, refer to this straightforward method:

http://jsfiddle.net/461jaLxt/6/

$('.clickableList').click(function(event) {
   event.preventDefault();
   $('#svgPlus').toggle();
   $('#svgMinus').toggle();
});
.types {
   font-size: 20px;
   font-family: arial;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="border">
   <div class="clickableList">
      <span class="types">Swap icons</span>
      <svg id="svgPlus" width="20px" height="20px" viewBox="0 0 74 74" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
         <title>noun_1776266_cc</title>
         <desc>Created with Sketch.</desc>
         <defs></defs>
         <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
            <g id="noun_1776266_cc_2" transform="translate(0.000000, -1.000000)" fill="#000000" fill-rule="nonzero">
               <g id="Group" transform="translate(0.000000, 0.637820)">
                  <polygon id="Shape" points="33 0.36218 33 33.36218 0 33.36218 0 41.3622 33 41.3622 33 74.3622 41 74.3622 41 41.3622 74 41.3622 74 33.36218 41 33.36218 41 0.36218 33 0.36218"></polygon>
               </g>
            </g>
         </g>
      </svg>
      <svg id="svgMinus" style="display: none;" width="20px" height="20px" viewBox="0 0 74 74" version="1.1" 
         xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
         <title>noun_line_1776294</title>
         <desc>Created with Sketch.</desc>
         <defs></defs>
         <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
            <g id="noun_line_1776294" transform="translate(-6.000000, -31.000000)">
               <g id="Group" transform="translate(0.000000, 0.637820)">
                  <polygon id="Shape" fill="#000000" fill-rule="nonzero" points="6 30.36218 6 38.36218 68 38.36218 68 30.36218"></polygon>
                  <rect id="Rectangle" x="0" y="0" width="74" height="69"></rect>
               </g>
            </g>
         </g>
      </svg>
   </div>
</div>


Explaining the Process

Upon clicking, the function toggles between displaying the plus and minus symbols alternatively. In the provided example code, notice the second SVG element with `style="display: none;"`, indicating initial invisibility (explaining why the minus appears hidden initially). This swapping functionality is achieved using jQuery's toggle() function, which reveals a hidden element and conceals it upon subsequent clicks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

obtaining data from various forms and showcasing it in the corresponding field according to the form's identification number

I have implemented 2 forms on a single page with different structures <div id="tabs-7"> <form action="/admin/languages" id="1" class="mainForm" method="POST"> <fieldset> <div class="widget"> ...

Is there a method to preserve the pressed/focused state when moving from one input box to the next?

While creating a form for a client, I encountered a requirement where the input box should change once clicked and retain that change even after it has been filled and the user moves to the next input box. Is there a way to achieve this using only HTML & C ...

When the beforeSend function of jQuery AJAX returns false, it triggers the $.ajaxError event

function load() { var url = buildUrl(null, true); $.ajax(url, { cache: true, dataType: 'json', beforeSend: function(xhr) { if (typeof plugin.cache[url] != ...

Is the .html page cached and accessible offline if not included in the service-worker.js file?

During the development of my PWA, I encountered an unexpected behavior with caching. I included a test .html page for testing purposes that was not supposed to be cached in the sw.js folder. Additionally, I added some external links for testing. However, w ...

Discover the ins and outs of utilizing the Google+ Hangout API specifically for chatting purposes

I am currently working on a webpage and I want to include a hangout button that will allow users to connect with me and start chatting automatically when clicked. Here is the code I have so far: <script src="https://apis.google.com/js/platform.js" asy ...

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...

The issue of `window.setTimeout` not functioning properly with Google Maps Marker/XML integration has been a persistent

I'm having difficulty displaying markers individually from my database by making them "fly in." Here's the Ajax call: $.ajax({ type: "GET", async: true, url: '<?php echo PATH;?>ajax/map_process.php ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...

Javascript's event.keyCode does not capture the Backspace or Delete keys in Internet Explorer

Looking to detect when the Backspace and Delete keys are pressed using javascript/jQuery, I have the following code: $("textarea[name=txt]").keypress(function(e){ var keycode = e.keyCode ? e.keyCode : e.which; if(keycode == 8){ // backspace ...

pattern to eliminate particular anchor elements

I am facing a challenge with a large HTML file that contains approximately 300 similar anchor tags that need to be removed: <a href="javascript:void(0);" onclick="javascript:thumbs(198, 0, 'architecture')" class="icon"></a> The prob ...

Is it possible for me to include &x&y&z in my Sass code?

When working with Sass, I have the following code: asdf{ &-b&-c {font-size: 16px;} } And I want the generated CSS to look like this: asdf.asdf-b.asdf-c{ font-size: 16px; } Is it possible to achieve this in Sass without having to repeat th ...

instructions on sending the complete product quantity to the payment gateway

I am currently in the process of developing an ecommerce website using Django. When a user clicks on checkout, an HTML billing form appears prompting them to enter their address and email information. Previously, I successfully passed data such as email t ...

Flashing bug in the outFunction of jquery hover()

My friends and I are working on a website for a class project, but we're running into a strange issue with the outFunction part of our hover function. Whenever the mouse hovers over an element, a grey square fades in using .fadeIn(), but then immediat ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...

How can I retrieve JSON data from an AJAX request on an HTML page?

How can I display my JSON data on an HTML page using this JavaScript code? $.ajax({ url : 'auth.json', type: "GET", dataType : "jsonp", success: function(result) { $.each(result, function(i, v) { // Loop through each record in ...

Is it secure to use a unique, static HTML/CSS website?

As a web developer, I am currently working on hosting a Wordpress-website for a client. However, my frontend development skills have improved significantly and now I feel inspired to create a simpler and more customizable version on my own. This website i ...

get direct access to the children of a specific div element

Here is the code snippet in HTML format. <div id="this"> <a href="xxx"> xx</a> <a href="yy"> yy</a> <a href="zzz"> zzz</a> aaa <a href="bbb"> bbb</a> ccc </div> I am look ...

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...