Traverse an SVG element using JavaScript

I have a beautiful star SVG that I created, and I want to use it instead of styling a span to create floating bubbles in my div. However, I'm facing some challenges in adapting my Javascript loop to incorporate the SVG for creating the bubbles, as opposed to using the span element.

"use strict";

// variables
var numBubbles = 60;
var minSize = 10;
var maxSize = 20;
var container = document.getElementById("container");

// get the size of a bubble
// Randomized between minSize and maxSize
function bubbleSize() {
  return Math.floor(Math.random() * (maxSize - minSize + 1)) + minSize;
}

// Get the location of a bubble.
// Between left=2% and left=98%.
function bubbleLocation() {
  return Math.floor(Math.random() * 96) + 2;
}

// Create a bubble using the
// previous two functions.
function createBubble() {
  var size = bubbleSize();
  var location = bubbleLocation();

  // create span
  var el = document.createElement("span");

  // style span
  el.setAttribute("style", "width: " + size + "px; height: " + size + "px; left: " + location + "%; box-shadow: " + "0px 0px 12px 2px #ff4e85;");

  // append span
  container.appendChild(el);

}

// Start adding bubbles.
(function startBubbles() {
  var i = 0;

  function addBubble() {
    if (i < numBubbles) {
      createBubble();
      i++;
    } else {
      clearInterval(inter);
    }
  }

  // Add a bubble every 500ms.
  // But we don't want too many bubbles...

  var inter = setInterval(addBubble, 300);

})();

https://codepen.io/smugfox/pen/KyNxLG

Answer №1

If you're looking to replicate multiple SVGs, you have a couple of options. One is to clone the SVGs using Node.cloneNode() within the createBubble() function...

var el = svg.cloneNode(true);

...Alternatively, you can continue using <span> elements and set the SVG as a background-image in your CSS:

span {
    background-image: url("/path/to/star.svg");
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    ...

Whichever method you choose, if you want to add a drop-shadow to your star, you'll need to incorporate that using a <filter> in the SVG file.

For an updated example, check out this pen: https://codepen.io/Sphinxxxx/pen/YEpbwZ
This pen uses cloned SVGs. Switch the value of cloneSVGs to false to utilize spans with background images instead.

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

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

"Ensuring Data Accuracy: Validating WordPress Fields with JavaScript

Can anyone provide assistance with this? I've been struggling for some time now. I am in need of a JavaScript code that can compare two fields in a contact form to ensure they match. For example, Phone Number and Phone Number Again. Both fields must ...

Using React's higher order component (HOC) in TypeScript may trigger warnings when transitioning from non-TypeScript environments

I have a simple HOC component implemented in React with TypeScript. export const withFirebase = <P extends object>( Component: React.ComponentType<P> ) => class WithFirebase extends React.Component<P> { render() { return ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code: var fs = require('fs'), path = require('path ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

JSX Script issue: the input prompt is missing

Greetings! I am currently working on a script to export JSON files from Adobe Illustrator. // Custom function for exporting prefixed objects function exportPrefixedObjects(doc) { // User input for prefixes and reference points var prefixInput = prompt( ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

"Create a function that allows for the dynamic addition of elements to a

I want to dynamically add more li elements, similar to the first one, by simply clicking a button. Unfortunately, the example provided on jsfiddle is not functioning as intended. document.onload = init; function init(){ document.getElementById('a ...

Having trouble loading images in JavaScript due to an issue with JSON: undefined.jpg not found

I'm struggling to concatenate my image names in this JavaScript code as a newbie, especially since it's pulling from JSON. Any assistance would be greatly appreciated! Below is the JS code snippet I'm working with: function log(msg){ ...

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

What causes the Material-UI Grid element to shift upon clicking it?

I have encountered an issue while developing a React app with Material UI. The problem arises on a specific page of the application. This particular page consists of text and a button aligned vertically, along with a second set of text and another button ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

A guide on utilizing Stripe's payment_intent_data feature to automatically send an email to the customer following a successful transaction

I am struggling to send an email to the client after a successful payment. The documentation mentions setting "payment_intent_data.receipt_email", but my code below is not working as expected (no emails are being received). How should I properly configur ...

Manipulation of CSS DOM elements for achieving responsive design

I am working with a div field that contains an input element and a label element, both set to display:block <div class="cf-full"> <input id="a" > <label class="helptext"></label> </div> In the standard view, the inpu ...

Expand a section of the webpage to fill the entire screen

I'm working with some HTML code that looks like this: <header>title</header> <content class="container-fluid"> <div class="row"> <div class="col-sm-3 leftside"> <ul> <li>test</li> ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...