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

Finding elements through their text representation

I am struggling to select an element using the text "SELECT PRODUCT" in the following HTML: <div style="font-family: franklin-gothic-urw; font-weight: 400; font-style: normal; font-size: 19px; opacity: 1; color: rgb(255, 255, 255);">SELECT&nbsp; ...

Does an invisible property value exist?

Instead of: if ( ! $('#XX').is(':visible) ) Is there a property named invisible? I tested that one out, but it seems to not work. Appreciate the help! ...

Any ideas on how to extract binary data from PHP passthru using a JavaScript ajax request?

I am facing an issue with retrieving and playing an audio file from a server using JavaScript. The ajax call in my code doesn't seem to callback, and I'm not certain if I'm handling the audio correctly in JavaScript. Below is the PHP file t ...

The Bootstrap navigation bar vanishes when viewed on mobile devices

I've integrated Bootstrap 5 with my navbar, but when viewed on a mobile device, the buttons disappear. Even hovering over them doesn't display anything. Is there a solution for this issue? Below is the code snippet: <nav class="navbar na ...

Managing input jQuery with special characters such as 'ä', 'ö', 'ü' poses a unique challenge

Hey there, I'm running into a bit of trouble with my code and I can't figure out why it's not working. Here's a brief overview: I created my own auto-suggest feature similar to jQuery UI autosuggest. Unfortunately, I'm unable t ...

Eliminating the vertical scroll on a webpage with the help of Bootstrap 5's responsive design capabilities

I've been tasked with converting a Figma design into an HTML page using Bootstrap 5. Take a look at the Figma design: https://i.sstatic.net/jo5Si.png However, there's an issue causing a vertical scroll bar to appear on the page. The culprit see ...

The list is slowly dissipating and shifting, rather than simply fading and a div moving above it

I'm trying to achieve a certain effect with two div elements - one containing text with the 'logo' class and the other being a list. When an element inside the list is clicked, I want the list to fade out while the logo slides up by a specif ...

Locate Checkbox by its Attribute Name and Value

On my webpage, there are multiple groups of checkboxes. In one particular group, I have added a custom "documentcategory" attribute to each checkbox. My goal is to identify all the checkboxes on the page that have the "documentcategory" attribute with a va ...

Tips on sending the total value of a form to a PHP script

Looking for help with a PHP script to calculate the sum of checked checkboxes with corresponding numeric values. For example, if checkbox 1 = 80; checkbox 2 = 21; and checkbox 3 = 15, and the user checks checkboxes 2 and 3, the PHP should output 36. I hav ...

Choose a minimum of one validation for the list item

When I have a form in JSP that includes a drop-down view with multiple options, I want to ensure that at least one option is selected before the form can be submitted. If no options are selected, the form should not be able to submit. Thank you in advance ...

Error encountered while using JQuery Ajax to invoke server-side method in ASP C#

How can I call a server-side method using AJAX in an ASP C# application? I have the below code in my aspx file: function editApp(appID) { $.ajax({ type: "POST", url: "Default.aspx/GetSquare", contentTy ...

Guide on creating a live connection between a slider and a canvas

Currently, I am working on implementing a slider that can dynamically adjust a specific value in the canvas, such as the radius of a circle. Although my code works as intended, I would like the canvas to update in real-time as I move the slider instead of ...

Dealing with Error 462 in Excel VBA When Using Internet Explorer

This function is designed to loop through the hrefs obtained from the GetData() function, navigate each page, retrieve specific data, and then move on to the next one. Sub CreateDatabase() Dim ieNewPage As InternetExplorer, TableRows As Object, TableR ...

The iPhone is having trouble resizing background images in Bootstrap 5 Carousel

While working on my website using the Bootstrap 5 carousel template, I encountered an issue with the carousel images not resizing correctly on my iPhone. The images appear zoomed in to the upper left corner and cut off on smaller devices. I've attemp ...

Perfecting the Radio Button Selection (because why not?)

Struggling to round the outer corners of three inline squared radio buttons with unique IDs. Need help fixing my CSS syntax - I can get each button to individually round its corners, but not just radio1 and radio3's outer corners. Check out the issue ...

Testing with Selenium to confirm the presence of a specific CSS attribute within the style attribute

I am looking to create a Selenium IDE test that will confirm the value of the bottom attribute in the "style" section below. How can I go about writing a test for this considering: The Xpath to the element is: xpath=/html/body/div/div[3]/div[2]/div/div/di ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

Arrange by alphabetical order using a dropdown menu

I am stuck and need some help! I have a working Itemlist with Angular, but now I want to add sorting by a select-box. It should look something like this: preview Here is a Plunker example: https://embed.plnkr.co/JYF0u9jBbsfyIlraH3BJ/ <div id="ideaLis ...

Guidelines for dynamically passing HTML attribute values into a CSS selector using a variable in Protractor

After successfully locating the button on the row using its value stored in the "title" HTML attribute, I am now faced with the task of passing a dynamic value to this attribute. To achieve this, I have declared it as a variable. However, I am unsure about ...

Tips for including <script> tags in Angular2

Is there a way to integrate the following script into my Angular page: <script> jQuery(function () { jQuery('#camera_wrap_1').camera({ transPeriod: 500, time: 3000, height: '490px', thumbnails: ...