What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png

When I click on the tab, it expands like this

https://i.stack.imgur.com/XNuBi.png

After expanding, I want the svg icon to change to something else. Currently, my code is not showing any errors but it's also not functioning as expected. I wrote a function that should change the icon to `icon-cancel.svg` after clicking on the element, but nothing happens. Here is my current code:

<!DOCTYPE html>
<html lang="en">
  <head>

    <style type="text/css">
      body {
        font-family: 'Roboto Condensed', sans-serif;
      }
      #side-chat {
        position: absolute;
        right: 100%;
        bottom:50%;
        z-index:9999999999999 !important;
        width: 150px;
        margin-right: -59px;
        transform: rotate(-90deg);
        display:flex;
        justify-content: center;
        align-items: center;
        color: #ffffff;
        border-radius: 10px;
        background: rgba(30, 175, 230, 0.5);
        text-decoration: none;
        padding: 15px;
        font-size: 25px;
        line-height: 20px;
        text-align: center;    
      }
      #olark-box-wrapper {
        position: absolute;
        z-index:99999999999999 !important;
        top: 400px;
        right: -300px;

        -webkit-transition-duration: 0.3s;
        -moz-transition-duration: 0.3s;
        -o-transition-duration: 0.3s;
        transition-duration: 0.3s;
      }
      #olark-box-wrapper.chatbox-open {
        right: 0
      }
      #olark-box-wrapper.chatbox-closed {
       right: -300px;
      }
      #habla_window_div {
        margin: 0 !important;
      }
      #side-chat img{
        margin-right: 10px;
        
      }
      #side-chat:hover,
      #side-chat:active {
       background: #22a7e5;
}
    </style>
  </head>
  <body>
<div id="olark-box-wrapper">

  <!-- Olark chat tab -->
    <a id="side-chat" href="javascript:void(0);" onclick="changeClass(); changeImage();">
      <img src="icon-chat.svg">
         Chat
    </a>

  <!-- Empty Olark chat box container -->
  <div id="olark-box-container"></div>

</div>

<!-- begin olark code -->
<script type="text/javascript" async> ;(function(o,l,a,r,k,y){if(o.olark)return; r="script";y=l.createElement(r);r=l.getElementsByTagName(r)[0]; y.async=1;y.src="//"+a;r.parentNode.insertBefore(y,r); y=o.olark=function(){k.s.push(arguments);k.t.push(+new Date)}; y.extend=function(i,j){y("extend",i,j)}; y.identify=function(i){y("identify",k.i=i)}; y.configure=function(i,j){y("configure",i,j);k.c[i]=j}; k=y._={s:[],t:[+new Date],c:{},l:a}; })(window,document,"static.olark.com/jsclient/loader.js");
  /* custom configuration goes here (www.olark.com/documentation) */
  //olark.configure('system.hb_detached', true);
  olark.configure('box.inline', true);
  olark.identify('xxxx-xxx-xx-xxxx');</script>
  <!-- end olark code -->
  <script type='text/javascript'>
    // Javacript function to toggle the class of the chat box wrapper
    function changeClass()
    {
      // Get the HTML object containing the Olark chat box
      var olark_wrapper = document.getElementById("olark-box-wrapper");
      // If the chat box is already open, close it
      if ( olark_wrapper.className.match(/(?:^|\s)chatbox-open(?!\S)/) ) {
        olark_wrapper.className = "chatbox-closed";
       
      }
      // Otherwise, open the Olark chat box
      else {        
        olark_wrapper.className = "chatbox-open";
        
      }
        
    }


  function changeImage(){
document.getElementById('side-chat').src = "icon-cancel.svg";
</script>
  </body>
</html>

Answer №1

To resolve the issue, start by opening the code within the svg file and locate the path element. Copy everything between the svg codes and then proceed to add an onclick event. It is recommended that you include the following line:

svg.innerHTML = 'the content you copied'
for the click event. Keep in mind that svg files are comprised of vectors, and the path codes define the icon displayed. As such, modifying these path codes will result in a change to the icon itself. Hopefully, this solution proves helpful.

var svg = document.querySelector('.svg');
        svg.addEventListener('click',()=>{
            svg.innerHTML=`
           <path d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path>
            `
        })
  .svg
        {
            width: 30px;
            cursor: pointer;
        }
 <h2>Click svg</h2>
    <svg aria-hidden="true" class="svg" focusable="false" data-prefix="fas" data-icon="bars" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z"></path></svg>

Answer №2

Make sure to check the "side-chat" element, as it is using the <a> tag without a src attribute. Consider updating the code from getElementById to querySelector for accessing the image inside.

 function swapImage(){
     document.querySelector('#side-chat img').src = "icon-close.svg";
 }

Answer №3

When modifying your function, ensure that you are updating the src attribute of the correct element. If you are looking to change the src from an <img> tag instead of an <a> tag, your selector needs adjustment.

document.getElementById('side-chat') - selects the <a> tag

To resolve this issue, simply assign an id to the <img> tag and refer to this id when making changes. You can use document.getElementById('imgId').src = "new image path" within your changeImg() function for the desired result.

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

Start up Angular with a Fire $http.get when the page loads

I am facing an issue where my $http.get() request is firing after the home page has already loaded. How can I ensure that the request fires before the page loads so I can utilize the returned data on the page? Here is a snippet of the routing code: var l ...

Obtaining the text of a span tag within a div using Selenium in C#

<div id="uniqueSummaryID" class="custom-text" data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0"> <span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_key_25.1.1.0.0">5</span> <span data-reactid=".0.0.0.3.0.0.1.0.0.0.0.$unique_ke ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Reset a form input using jQuery

There is an ajax method in place that reloads only a specific div upon receiving a service response. success: function (response) { $( "#list" ).load(window.location.href + " #list" ); $( "#badge" ).load(window.location.href + " #badge" ); $ ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Strong tags within MFC

Is it possible to create labels in MFC (Static text) that contain both bold and non-bold text? For instance, something like this: "I want my label to have a mix of styles like this" Any suggestions on how to achieve this? I am aware that I can change ...

Using Bootstrap, jQuery, and PHP to dynamically load input fields in a modal window

I am looking to dynamically load input fields in a modal window using PHP. While researching, I came across suggestions to utilize AJAX for this purpose. However, I have limited knowledge about AJAX. The plan is as follows: 1) When the user clicks on the ...

EJS unable to display template content

I am having an issue with rendering a template that contains the following code block: <% if(type === 'Not Within Specifications'){ %> <% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% ...

What is the process of utilizing a <li> for a hover selector in jquery?

I've encountered an issue with a list that I am trying to modify its content when hovering over them. Despite using the id as a selector for triggering the hover function, all list items change color instead of just the intended one. The challenge lie ...

Substituting Div containers with elements imported from external files

Imagine I have <div> <div id="stuff"> <!-- stuff --> </div> </div> Could I move the content of <div id="stuff"> into a separate file named stuff.html, and then replace the code above with something simi ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...

ngAnimate - Animation not activating on recurring custom directive

I am trying to implement ngAnimate on a custom directive that is repeated using ng-repeat in my AngularJS application. The animations function correctly when I use ng-repeat on a simple HTML list-item. However, when I replace the list-item with a custom di ...

Utilizing the require pattern to integrate JavaScript functionality into HTML

Have: project |- consume_script.js |- index.html Need index.html to be like: <html> <head> </head> <body> <script src="consume_script.js"></script> </body> </html> Issue: consume_script ...

Ways to abbreviate a URL using Next JS

While working on my Next.js application, I encountered an issue with passing an object between pages. To achieve this, I compressed my array of objects into JSON using JSON.stringify(result) on the index page and then parsed it on the second page using JSO ...

What is the proper way to correctly invoke NuxtServerInit?

Code snippet from the VUEX repository: export const state = () => ({ z: 'sdfjkhskldjfhjskjdhfksjdhf', }); export const mutations = { init_data_for_firmenistorie2 (state, uploadDbFirmenistorieData){ state.z = uploadDbFirmenistorieD ...

Begin a fresh page within a separate window, proceed to print the contents, and subsequently close the window

I am facing some difficulties with this code. I am attempting to use the "onClick" function to change the image once it is clicked, open a new page in a new window, print the newly opened window, and then close it. The issue I am encountering is that while ...

Incorporating a Bootstrap input group within a <td> element of a table

Encountering an issue when attempting to include a bootstrap input-group-addon with the input field nested inside a <td> tag within a table. Once all necessary classes are applied, there appears to be some spacing between the sign and the input field ...

I'm curious if there is a specific jQuery event that triggers right before an element loses focus or right before the next element gains focus

I am facing a situation where I have two input elements in a form that are closely connected. The first element triggers an ajax call to check for existing data in the database when the user tries to move away from it, while the second element opens a moda ...

Is it possible to ensure uniformity in the appearance of all images with MVC Image Handling?

I'm currently developing an MVC 4 application that allows users to upload images. These uploaded images are then displayed in a different view. Users can upload images up to 10MB in size, which are then resized to 800 x ? pixels using the WebImage (Sy ...