Is there a keen eye out there that can help me pinpoint the mistake in this SVG/Javascript function?

I have created a series of SVG circles that are meant to alternate in color between blue and red with each click. However, I am experiencing some inconsistency in the behavior. In my local environment, the color doesn't change to red until the second click. When I tried running the code in jsFiddle, one circle works while the other does not, even though the code is identical, and both throw the same error in the console.

[Error] ReferenceError: Can't find variable: changeColor1 onclick (_display:79)

     var shapeClick = document.getElementById("circle0").addEventListener("click", changeColor);
        var clicks = 0;
        var colorToggle = true;

        function changeColor() {
          var color = colorToggle ? "#ff0000" : "#1dacf9";
          circle0.setAttribute('fill', color);
          colorToggle = !colorToggle;
        }


        var shapeClick = document.getElementById("circle1").addEventListener("click", changeColor1);
        var clicks = 0;
        var colorToggle = true;

        function changeColor1() {
          var color = colorToggle ? "#ff0000" : "#1dacf9";
          circle1.setAttribute('fill', color);
          colorToggle = !colorToggle;
        }
<svg id="table1" width="66%" height="100vh" viewBox="0 0 700 666">

    <circle id="circle0" class="circles" cx="170" cy="125" r="20"     fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor()"/>

    
          <circle id="circle1" class="circles" cx="250" cy="45" r="20"      fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor1()"/>
      
      </svg>

There must be a more efficient way to achieve this functionality, especially if scaling it up to include 100 circles. It seems challenging without resorting to a significant amount of code.

Answer №1

When dealing with variables in your situation, it appears that you are redefining existing variables which causes both circles to reference the same toggle value.

var shapeClick = ...

...

var shapeClick = ...

Furthermore, using both onclick="function()" and addEventListener is redundant as they serve the same purpose.

To streamline your code, consider implementing a few key strategies:

  1. Establish an object to store toggle states. Each circle's ID should act as a key, with values set to either true or false indicating the state of each circle.
  2. Create a single handler function and utilize event.target.getAttribute('id') to determine which circle was clicked.

Your revised code should resemble something like this:

var state = {};

var circleClickHandler = function (event) {
    var id = event.target.getAttribute('id');
    var color = state[id] ? "#ff0000" : "#1dacf9";
    event.target.setAttribute('fill', color);
    state[id] = !state[id];
};

// Iterate through each circle element in the DOM
document.querySelectorAll('circle').forEach(function (element) {
    element.addEventListener('click', circleClickHandler);
});

Answer №2

It appears that you have overlooked the opening svg tag in your code.

Link to JS Fiddle

<svg>
<circle id="circle0" class="circles" cx="170" cy="125" r="20" fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor()"/>

<circle id="circle1" class="circles" cx="250" cy="45" r="20" fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor1()"/>
</svg>

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 position a search icon on the right side using CSS?

I am trying to figure out how to display a search icon image on the right side using CSS, but so far I have been unsuccessful. Here is the code that I have: The CSS code: .search { background: url(../images/icons/search.png) no-repeat; display:in ...

Dynamic Visualizations with D3.js: Live Charts for Real-Time

This is my first time using D3.js and I am attempting to create a basic sparkline graph. The graph should have time on the X-axis and numbers up to 1000 on the Y-axis. I have a web socket server that sends random numbers up to 1000 to clients. My goal is t ...

Managing simultaneous access to a variable in NodeJS: Best practices

For instance: var i = 0; while(true) http.request('a url', callback_f); function **callback_f**(){ **i++**; } In this straightforward scenario, multiple requests could unintentionally increase the value of i simultaneously. How can I creat ...

Using Django to load a template following an AJAX request

Currently, I am utilizing Django templates in one specific template where I load multiple divs with content by executing two AJAX requests simultaneously to improve performance. The main issue arises from a view element added at the end of this template, ...

Having trouble with the auto suggest feature in PyCharm with Material Design Lite?

Struggling with setting up a fresh Django project in PyCharm and encountering issues with HTML code autocompletion. I've integrated Material Design Lite as the front-end framework, storing the files in a static folder within the project. I attempted ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

Employing the new operator in conjunction with a variable

Is there a way to achieve the following scenario: var foo = function(){ this.value = 1; } var bar = "foo"; var baz = new bar(); alert(baz.value) // 1 Specifically, I am looking for a method to instantiate an object using its string name. Any sugge ...

The left and right DIVs are not automatically adjusting to the height of the container

I am currently working on a grid layout consisting of 9 div tags, creating 3 rows with 3 divs in each row. Within this grid, each div is supposed to have a background image, except for the second div in the second row. My main challenge lies in getting th ...

Incorporate Three.JS into Meteor for enhanced functionality

Currently, I am experimenting with integrating Meteor and Three.JS. The specific meteorite package for Three.JS that I am utilizing can be found here: https://github.com/nozpheratu/three-meteor. Despite being able to perform basic functions in Three.JS, I ...

The form validation in Bootstrap 5 seems to be having some trouble triggering

Here is the form setup for allowing users to change their account password: <div class="signup-form-small"> <form method="post" name="frmPassword" id="frmPasswo ...

What is the best way to output neat and tidy JavaScript code from a custom view helper in Rails

As I was working on my update.js.erb file using Rails 3, I realized that I was repeating a lot of code. To simplify things, I attempted to move it all into a helper function. However, I encountered an issue where the helper was not producing clean JavaScri ...

I'm having trouble with my AngularJS Spinner directive

Check out this simple directive I created to display a spinner on my button while something is happening remotely: http://plnkr.co/edit/rAJ4X7A3iidmqUD2M63A?p=preview Here's the html: <!DOCTYPE html> <html ng-app="app"> <head> ...

Generating unique names based on input from users

We are working with an array containing names and an input field where users can enter a string to receive name suggestions. The array includes names like Alex and Anna, and when the user types "a," we want to suggest these names. Below is the code snippet ...

Arranging inline-flex elements within a div container

I have been struggling to position two elements side by side within a single div, where the second element should be on the right side. <div className={classes.container}> <div className={classes.first}> First </div> <d ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Upgrading from ng-router to ui-router in the Angular-fullstack application

issue 1: url:/home, templateUrl: 'index.html is appearing twice. problem 2: views: templateUrl: 'views/partials/main.html is not visible at all. What am I doing wrong? How can I effectively incorporate ui-router into yeoman's angular-fulls ...

Issue in Babel: The preset 'latest' could not be located in the directory even though it was installed globally

I executed a global installation of Babel using: npm install -g babel-cli npm install -g babel-preset-latest Although it is generally not recommended to install Babel globally, I find it preferable in order to maintain a clean directory structure without ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Implementing custom CSS styles to a component in real-time with ng-style

When I use an angularjs component to create stylized pictures, the style is not applied correctly on the first visit to a page (refreshing the page shows the correct style). The CSS that should be applied is generated dynamically based on the height and wi ...

Why is the feedback section showing a horizontal scrollbar?

I'm puzzled as to why a horizontal scrollbar is appearing in the feedback section. I've examined the elements but can't seem to pinpoint the issue. ...