Having trouble changing the <image> href with JavaScript

This code successfully changes the value of href, as evidenced by the alternating confirmation alerts. However, the <image> element remains unchanged. What could be causing this issue?

var onImg= "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg";
var offImg= "https://upload.wikimedia.org/wikipedia/commons/3/3d/1951_Unión_1-Colón_1.png";
function toggleImage() {
  if (this.href == onImg) {
    alert('turning off');
    this.href = offImg;
  } else {
    alert('turning on');
    this.href = onImg;
  }
}
<ul class="board">
  <li>
     <svg width="100%" height="100%" viewBox="0 0 2911 2521">
        <image clip-path="url(#hexagonal-mask)" height="100%" width="100%" href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg" onclick="toggleImage()"/>
    </svg>
  </li>
</ul>

Answer №1

Here are a few important points to consider:

  • Ensure that you define the clipPath for your image to avoid potential issues with click events not firing, especially in Firefox.
  • When attaching an event handler as an attribute, remember that this may not be passed automatically, so make sure to pass it yourself from the event handler.
  • Remember that SVGImageElement.href is an SVGAnimatedString, not a simple string. To retrieve or modify its value, access or set its .baseVal property:

var onImg= "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg";
var offImg= "https://upload.wikimedia.org/wikipedia/commons/3/3d/1951_Unión_1-Colón_1.png";
function toggleImage(img) {
  if (img.href.baseVal == onImg) {
    alert('turning off');
    img.href.baseVal = offImg;
  } else {
    alert('turning on');
    img.href.baseVal = onImg;
  }
}
<ul class="board">
  <li>
     <svg width="100%" height="100%" viewBox="0 0 2911 2521">
        <image height="100%" width="100%" href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg" onclick="toggleImage(this)"/>
    </svg>
  </li>
</ul>

Alternatively, setting the attribute and using a correct event handler can simplify things:

var onImg= "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg";
var offImg= "https://upload.wikimedia.org/wikipedia/commons/3/3d/1951_Unión_1-Colón_1.png";
document.querySelector("image").addEventListener("click",  function toggleImage(evt) {
  const current_value = this.getAttribute("href");
  if (current_value == onImg) {
    alert('turning off');
    this.setAttribute("href", offImg);
  } else {
    alert('turning on');
    this.setAttribute("href", onImg);
  }
});
<ul class="board">
  <li>
     <svg width="100%" height="100%" viewBox="0 0 2911 2521">
        <image height="100%" width="100%" href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg/1000px-CSIRO_ScienceImage_3881_Five_Antennas_at_Narrabri.jpg"/>
    </svg>
  </li>
</ul>

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

What is the best way to remove extra information from a redirect URL?

Implementing Discord login OAuth2 in JavaScript has been quite a journey. I have managed to redirect to '/auth' upon completion, but the URL for that page comes with additional information like '/auth#token_type=Bearer&access_token=12eka ...

Is there a method for verifying the application signature in Ionic?

For the past 2 days, I've been on a quest to find information about app certificate validation libraries/functions in Ionic. After discovering SignatureCheck.java for Android (link: enter link description here), I wonder if there is a similar solution ...

Is it possible to include parameters within a print() function in JavaScript?

Can anyone help me figure out how to add parameters to a print function? I only want to print a specific table, but when I try to print it, the entire page gets printed instead. Here's my code: let tableContent = document.getElementById('tablen ...

Link various data to various text boxes using a common ngModel property in Angular 8

In my project, I am working on creating a time-picker that will open when the user focuses on a text-box. The challenge I'm encountering is that although there are multiple text-boxes on a single page, binding the selected value from the time-picker u ...

Utilizing HTML and Javascript to set timers on various elements by targeting classes with the get

I'm facing an issue with my PHP code that echoes a list of files in a directory. Everything seems to be working fine, but when I try to use Javascript to hide the files after 5 seconds, it just doesn't work. Can you help me figure out what needs ...

Three.JS 3D Model successfully integrated but appears to be invisible on the screen

I've been trying to incorporate a 3D model into my website using three.js, but I've run into an issue. Despite loading the MTL and OBJ files successfully according to the network tab in developer tools, the 3D model remains invisible on the page. ...

Database interaction menu for retrieval and posting of options

Is there a way to create an option list that retrieves data dynamically from a database and allows the user to select a record to post ($_POST) to the database? I have attempted to do this but have encountered an issue where the record is not being posted: ...

Leveraging AJAX for retrieving a targeted DOM element (with Javascript instead of jQuery)

Can you explain how to utilize AJAX (without using jQuery, but in plain JavaScript) to fetch a specific DOM Element from a page on the same domain and display it? For instance, focusing on the DOM element identified with the id of "bodyContent". I am curr ...

Creating a cutout effect on 3D text within a Geometry using Three.js

I am looking to convert my 3D text into Geometry so that I can utilize it with CSG (I have also used a Three.js CSG wrapper) in order to subtract it from another object, similar to the scenario described in this question. Here is my 3D text: loader.load( ...

The webpage appears to be experiencing issues with the append() function

I'm having trouble appending a form and it's not working properly. Can anyone help me with a solution? Whenever I click the button below: <div class="col-md-4"> <span href="" class="btn btn-info btn-lg dashboard-icon append">Assig ...

Is it possible to utilize CSS for styling page.aspx controls?

Is it possible to apply CSS styles to the controls on page.aspx? Can CSS be used for everything on the page? ...

Remotely Connecting to an SQL Table

In order to achieve my ultimate goal, I am looking to build a web application that can read and write data to and from a central table located on a main computer. The aim is for any changes made on one device to be reflected when the table is accessed from ...

Encountering an issue with setting up Firefox profile in protractor when using selenium webdriver configuration

var p = require("p"); var ChromeProfile = require("chrome-profile"); var createChromeProfile = function(settingsMap) { var deferred = p.defer(); var chromeProfile = new ChromeProfile(); for (var k in settingsMap) { chromeProfile.setSe ...

Issues encountered when using Jquery click event for multiple buttons isn't functional

I am using PHP to fetch deliveries from MySQL, and I have a scenario where when the user clicks on the Accept button, I want to display one form, and if they click on Revision, another form should be shown. While I know how to achieve this functionality, i ...

Obscure issue encountered during production: `Type Error: e is not defined`

After putting my Vue app into production, I encountered a perplexing issue with a specific component that throws an error message I can't track down. The problem seems to be related to the bundling process since it only occurs in production mode. Ste ...

HTML Template tags: querySelector only returns null values

I'm currently working on an educational website, but I've run into a problem that I can't solve on my own. Here's the template I created: <div class="row" style="height: 75%;" align="center" id="room-list"> <template id="ro ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

JavaScript: Preventing Duplicate Keystrokes in Keyboard Input

Currently, I am working on a snake game project as part of my JavaScript course. I have encountered an issue where the game registers a collision when two keys are pressed simultaneously, even though there is no visual collision. https://i.sstatic.net/j42 ...

What are the benefits of embedding JavaScript code directly into HTML?

Currently implementing the angular js routing concept which involves creating two html files to be routed on certain options being clicked The main HTML code includes ng-view <div ng-view> </div> First HTML file <h1>This is the first ...