Why isn't the color of the circle changing in the console when I type this.fill = "black"?

I am creating circles as a hobby, using a function to generate them. However, I am facing an issue with changing their parameters in the console after creation. Specifically, I am unable to change them in this manner and I'm wondering why not.

a.fill = "black"; does not successfully update the circle object's parameter when executed in the console.

const container = document.body
let svgContainer = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgContainer.style.width = "100vw"
svgContainer.style.height = "100vw"
svgContainer.setAttribute("viewBox", "0 0 500 750");
container.appendChild(svgContainer);

function makeCircle(cx, cy, r, fill, stroke, id) {
  this.cx = cx;
  this.cy = cy;
  this.r = r;
  this.fill = fill;
  this.stroke = stroke;
  this.id = id;
  let newCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
  newCircle.setAttribute("cx", cx);
  newCircle.setAttribute("cy", cy);
  newCircle.setAttribute("r", r);
  newCircle.setAttributeNS(null, 'fill', fill);
  newCircle.setAttributeNS(null, 'stroke', stroke);
  svgContainer.appendChild(newCircle);
}

let a = new makeCircle(50, 300, 20, '#493fea', 'green');

Answer №1

Is it possible to modify their parameters in the console after they are created? Why does it not work?

The reason you cannot do this is because when you create a new object with a property like cx, for example, and separately create a

<circle cx="..." />
, the property in your created object and the attribute on the <circle /> are not connected to each other once they are initially set. In order to change the property and have the attribute updated as well, you need to establish this connection.

Here's an example that demonstrates how to achieve this. It involves a generic function that takes the name of an element and a list of its specific SVG attributes, returning a function similar to your makeCircle but with properties linked to the object.

Instead of individual attributes like

makeCircle(cx, cy, r, fill, stroke, id)
, this generic function accepts a single object with the desired attributes:
makeCircle({ cx, cy, r, fill, stroke, id })
.

This example includes various tools such as converting attribute names to property definitions, creating properties that get/set values from attributes, and defining shared SVG attributes for elements.

It also demonstrates how to dynamically create SVG elements using factory functions, define properties based on specified attributes, and manipulate those properties later on.

While this is a simple example, there is room for improvement in the code. For instance, all properties currently return strings instead of numbers.

Answer №2

If you're looking to have some fun while creating circles, try this quirky approach:

Start by running the SO snippet and clicking on the viewBox.

customElements.define("svg-measles", class extends HTMLElement {
  connectedCallback() {
    this.style.display = "inline-block";
    this.style.width   = "100vw";
    this.style.height  = "100vh";
    this.colors = ['red','orange','yellow','green','blue','indigo','violet'];
    this.innerHTML = `<svg style="width:100%;height:100%" viewBox="${this.getAttribute("viewbox")}"/>`;
    let svg = this.querySelector("svg");
    this.makeCircle("50%", "50%", 10, '#493fea', 'green');
    this.onclick = (evt) => {
      let svg = this.querySelector("svg");
      let pt  = svg.createSVGPoint();
      pt.x = evt.clientX;
      pt.y = evt.clientY;
      let {x,y} = pt.matrixTransform(svg.getScreenCTM().inverse());
      this.makeCircle(x, y, 10, 'green', 'yellow');
    }
  }
  makeCircle(cx, cy, r, fill, stroke, id) {
    this.colors.unshift(fill = this.colors.pop());
    this.querySelector("svg")
        .insertAdjacentHTML("beforeend", 
                            `<circle cx="${cx}" cy="${cy}" r="${r}" fill="${fill}" stroke="${stroke}"/>`);
  }
});
<svg-measles viewBox="0 0 300 200"></svg-meales>

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

Discover the precise number of columns and rows that make up a circle

Is there a way to display a popup message when clicking on a circle in the array to see the number of rows and columns that circle is from the starting point (1,1)? I'm looking for assistance with implementing this feature. var c = document.getEleme ...

"Struggling with Mongoose's Inaccurate Value Saving

When I attempt to create an object from a post request, I notice that the fields coming from the request body are being set to the field name itself. Strangely, I am not receiving any errors but the JSON object I expect in the response is not what I am get ...

Guide on setting up the installation process of Gulp jshint with npm?

Having trouble with the installation of JSHint. Can anyone point out what I might be doing incorrectly? This is the command I am using: npm install --save-dev gulp-jshint gulp-jscs jshint-stylish Getting the following error message: "[email protect ...

What is preventing me from setting a value to a React hook input?

How do I capture user input and assign it to a React hook? const { specName, setSpecName } = useState(""); <input name="name" onChange={e => { setSpecName(e.target.value) }} value={specName} className="specia ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

Ways to conceal an item by considering the size of a different element

I have a question about displaying content within a div element. I want to show a "show more" button only if the content inside the div exceeds a max height of 530px. Otherwise, the button should remain hidden. Here is the code snippet I'm using: Ja ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Tutorial on integrating jquery ui's '.droppable' feature with the jQuery '.on' method

I have a main div with three inner divs labeled 1, 2, and 3 as shown below: <div id="main"> <div style="height:30px; background-color:yellow;" class="bnr">Banner</div> <div style="height:30px; background-color:yellow;" class=" ...

Updating the jQuery mobile webpage

I have set up a small demo with two pages - the Home page and the Team 1 page. By clicking on the navigation menu, you can navigate to the Team 1 page from the Home page. However, if you are already on the Team 1 page and click on the Team 1 button again ...

How to dynamically reset an ng-form in Angular

After reviewing the following resources: Reset Form in AngularJS and Angular clear subform data and reset validation, I am attempting to develop a flexible form reset/clear function that would resemble the code snippet below: $scope.clearSection = functio ...

How to refresh an image in Next.js using setState even when the src path remains unchanged

Define a state variable: const [picture, setPicture] = useState(null); Assuming the picture is initially set to "123" and even after updating the image, the value remains "123". How can I reload the Image? <Image src={profileurl + picture} alt="profile ...

Encountering a Next.js error while trying to link to a dynamic page

My current folder structure is as follows: - blog (directory) -- index.js (list of all blog articles) -- [slug].js (single article) Whenever I am inside index.js, the code looks like this: const Blog = props => { const { pageProps: { articles } } = ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

Using the ng-repeat directive along with the string replace expression allows for dynamically

Struggling to find a way to remove a substring within an angular expression while using the ng-repeat directive. The controller resides in an external JavaScript file, and here is the corresponding HTML code snippet. function myController($scope, $http ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

What steps should I take to move the content to the bottom of the page once the promise is fulfilled within the function?

I have a showBoxConfirm function that confirms user actions. After clicking the button, it triggers the clickMethod function. The result variable will store the confirmation response, and if it returns false, the function will terminate. However, the sho ...

Transition from traditional class-based components to functional components

I am utilizing the ref from the parent class to access the child class. However, in this scenario, I want to access the child functional component from the parent class. In the parent class: class Waveform extends Component { constructor(props){ s ...

Error: Unable to access attribute 'item_name' as it is not defined

I'm new to React.js and I'm attempting to build a todo app. The main feature is a text input field where users can add items to their list. When I run "npm start," the app works perfectly and displays the expected output on my designated port. Ho ...

Tips on how to adjust the HTML5 input type attribute in ios 5 to display the current date and time

I attempted the solution that seemed most straightforward, but unfortunately it didn't yield the desired outcome... const element = document.getElementById("element-id"); element.value = new Date().toString(); The code requires a string input, but h ...