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

Symfony2 and asynchronous JavaScript and XML (AJAX)

Is there a way to perform asynchronous actions in Symfony2 without having to refresh the page? I haven't been able to find any information about this in the official "Book" or "Cookbook". (The only mention I came across was 2 sentences about hinclude. ...

Image not appearing on basic HTML website

This particular issue has left me completely puzzled. After removing all the unnecessary elements from a problematic website, I am now left with an extremely basic and minimalistic site: <!DOCTYPE html> <html lang="en"> ...

Function that returns an array

Hey there, wondering about variable scope in closures! I've come across a lot of questions on this topic but haven't found the solution to my issue. Here's the code snippet: var teams = []; var players = []; var getRoles = function(roleL ...

What is the best way to make a table fill 100% of the available height

Is this a Repetitive Question? How to stretch an HTML table to 100% of the browser window height? Just like the title says, I am looking for a way to make my table element stretch to 100% height even when the content does not entirely fill the page&ap ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Generate an HTML table dynamically from a PostgreSQL query

I am facing a challenge that may be simple for experienced individuals but is proving to be difficult for me as a newbie. The task at hand involves retrieving JSON data from a database query and displaying it in an HTML table using Node.js, Express, and Po ...

Using jQuery to implement multiple FadeIn effects

Here is the code that I have written: $('.frame').each(function(){ $(this).click(function(e){ var id = $(this).attr('id'); e.preventDefault(); $('.active').removeClass('active').fadeOut(8 ...

Unexpected behavior observed with Mui theme breakpoints

I have defined breakpoints for my MUI React-based app like so export const lighttheme = createTheme({ palette: palette, typography: typography, breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536, ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...

Utilize the dynamic duo of GridLayout and ScrollView within the Famo.us JS framework

I'm attempting to incorporate a grid layout into a scroll view using famo.us (with angular), and the most straightforward approach seems to be working. <fa-view> <fa-scroll-view fa-pipe-from="eventHandler" fa-options="scrollView"> ...

Is there a way to automatically override the CSS cursor style?

Issue with SCSS styling on image link I attempted to modify the cursor style from pointer to default, but after saving and reloading my React app, the change did not take effect. I tried writing some code, but it seems that Stack Overflow is indicating an ...

Is jQuery the solution for tidying up messy HTML code?

Is there a way to clean up this markup using jQuery? <span style="font-size:19px"> <span style="font-size:20px"> <span style="font-size:21px"> Something </span> </span> </span> I'm looking to tra ...

I'm struggling to make the jquery parentsUntil function work properly

Would appreciate some help with using the jquery parentsUntil method to hide a button until a radio box is selected. I've been struggling with this for a few days now and can't seem to figure out what I'm doing wrong. Any insights would be g ...

Lock GridView headers when only scrolling vertically

I am facing an issue with my gridview on an aspx page. The gridview is wider than the page itself, so I want the headers of the gridview to scroll horizontally along with the content, while remaining fixed vertically. Can anyone help me achieve this? I hav ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Calling Number() on a string will result in returning a value of NaN

Currently, I am working on the following code snippet: app.put("/transaction/:value/:id1/:id2", async(req,res) => { try { const {value,id1,id2} = req.params; const bal1 = await pool.query("Select balance from balance where id=$1",[i ...

I'm curious if anyone has had success utilizing react-testing-library to effectively test change events on a draftJS Editor component

​I'm having trouble with the fireEvent.change() method. When I try to use it, I get an error saying there are no setters on the element. After that, I attempted using aria selectors instead. const DraftEditor = getByRole('textbox') Draf ...

Tips for managing variables to display or hide in various components using Angular

In this example, there are 3 main components: The first component is A.component.ts: This is the parent component where an HTTP call is made to retrieve a response. const res = this.http.post("https://api.com/abcde", { test: true, }); res.subscribe((r ...

The hover effect is not functioning upon loading

Demo: http://jsbin.com/afixay/3/edit 1) Hover over the red box. 2) Without moving the cursor, press ctrl+r to reload the page. 3) No alert will appear. However, an alert will pop up once you move the cursor away and hover back over the box. The issue h ...

IE8 - Unable to use rgba()

I'm currently facing an issue with RGBA() manipulation in jQuery while using IE 8. Here's the code I have so far: $('.set').click(function (e) { var hiddenSection = $('div.hidden'); hiddenSection.fadeIn() . ...