Can you assist with transforming the html, css, and js code into a svelte format using style lang="postcss" specifically for tailwind?

I'm attempting to transform this shining button from a codepen I discovered into a svelte component, but for some reason the sparkles don't appear. I'm unsure if it's relevant, but I'm also utilizing Tailwind CSS, so my style tag has the attribute lang="postcss". Here's the codepen where I sourced these from: https://codepen.io/jh3y/pen/LYJMPBL. These elements constitute the button:

HTML:

<div class="sparkle-button">
  <button>
    <span class="spark"></span>
    <!-- <span class="spark"></span> -->
    <span class="backdrop"></span>
    <svg class="sparkle" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M14.187 8.096L15 5.25L15.813 8.096C16.0231 8.83114 16.4171 9.50062 16.9577 10.0413C17.4984 10.5819 18.1679 10.9759 18.903 11.186L21.75 12L18.904 12.813C18.1689 13.0231 17.4994 13.4171 16.9587 13.9577C16.4181 14.4984 16.0241 15.1679 15.814 15.903L15 18.75L14.187 15.904C13.9769 15.168...
    </svg>
    <span class="text">Generate Site</span>
  </button>
  <div class="bodydrop"></div>
  <span aria-hidden="true" class="particle-pen">
    ...
  </span>
</div>

CSS:

*,
*:after,
*:before {
    box-sizing: border-box;
}
:root {
    --transition: 0.25s;
...
}

button svg {
    inline-size: 1.25em;
    translate: -25% -5%;
}

JS:

// JavaScript used to set randomness for particles.
// Could be done via SSR

const RANDOM = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
const PARTICLES = document.querySelectorAll('.particle')
PARTICLES.forEach(P => {
    P.setAttribute('style', `
        --x: ${RANDOM(20, 80)};
        --y: ${RANDOM(20, 80)};
        --duration: ${RANDOM(6, 20)};
        --delay: ${RANDOM(1, 10)};
        --alpha: ${RANDOM(40, 90) / 100};
        --origin-x: ${Math.random() > 0.5 ? RANDOM(300, 800) * -1 : RANDOM(300, 800)}%;
        --origin-y: ${Math.random() > 0.5 ? RANDOM(300, 800) * -1 : RANDOM(300, 800)}%;
        --size: ${RANDOM(40, 90) / 100};
    `)
})

Answer №1

It is not recommended to use DOM querying because the elements will only exist once the component is fully mounted.

Instead of manually duplicating particles, utilize {#each}, and apply randomized styling directly in the HTML.

The CSS used in the demo targets elements outside the component, which would require the use of :global(...). In a real application, styling the body with a button might not be ideal.

To condense JS and HTML:

<script>
    const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
</script>

<div class="sparkle-button">
  <button>
    <span class="spark" />
    <span class="backdrop" />
    <svg class="sparkle" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      ...svg path data...
    </svg>
    <span class="text">Generate Site</span>
  </button>
  <div class="bodydrop" />
  <span aria-hidden="true" class="particle-pen">
    {#each { length: 20 } as _}
      <svg
        class="particle"
        ...randomized styling...
      </svg>
    {/each}
  </span>
</div>

REPL

Move the random helper function into @const within the #each loop to eliminate the need for a script tag altogether. Style properties can also be set using style:property, although this may result in significant duplication.

{#each { length: 20 } as _}
  {@const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)}
  <svg
    class="particle"
    ...randomized styling...
  >

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

Selenium-webdriver is having trouble locating an element through the CSS selector

I encountered an issue while using selenium-webdriver in JavaScript to input a value into a field. Here is my test.js code: async () => { let driver = await new webdriver.Builder().forBrowser("chrome").build(); try { await driver.get("http://te ...

What is the most effective method for attempting an AJAX request again after it fails with the help of jQuery?

Here is a suggestion for handling ajax errors: $(document).ajaxError(function(e, xhr, options, error) { xhr.retry() }) An improvement could be incorporating exponential back-off strategies ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

Utilizing HTML injection to access both the Chrome API and global variables

I am currently developing a new Chrome Extension and am diving into the process for the first time. My extension involves injecting an HTML sidebar into web pages, adding JavaScript functions to the header, and allowing users to interact with buttons on th ...

Disabling the smooth scrolling feature on tab navigation

I am using smooth scroll JS to navigate from a menu item to an anchor located further down the page. However, I am encountering an issue where my tabs (which utilize #tabname) also trigger the scroll behavior when clicked on. Is there a simple modificati ...

The error message "Uncaught ReferenceError: $foo is undefined, please check your

Currently, I am working on a project to toggle the expansion and collapse of individual divs on a click event using jQuery within the Laravel Spark framework. Most of my code is based on the solution provided in response to this query. Upon clicking the s ...

What is the most efficient way to update a particular item in an array within a React component's state while maintaining its conventional approach?

When working with React component state, I often struggle with manipulating a specific item in an array. Take this example: state={ menus:[ { id:1, title: 'something', 'subtitle': 'another something', switch ...

Retrieving objects from JSON data

I'm facing a challenge in creating a React component that showcases test results from various courses. The issue lies in accessing the scores object within the provided JSON file. Here is an excerpt from the JSON data I am currently working on: [ ...

Generating an array of quarter numbers and year based on the current date in Node.js using Moment.js - a simple guide

I need to generate an array of quarter numbers and year numbers based on the current timestamp in Node.js. For instance, if the current quarter is Q1 and the year is 2020, I want to create an array similar to the one below. quarters = ['Q2-2019' ...

React Error: "SharedArrayBuffer is not defined" Firefox encountered a problem

I am encountering an issue with my React app that was created using 'create-react-app' along with the jsdom NPM package. Strangely, the application is throwing an error upon loading exclusively in Firefox, as it works perfectly fine in Chrome and ...

Sinon causing 'unsafe-eval' error in Chrome extension unit tests

Recently, I've been conducting unit tests on my Chrome extension using Mocha, Chai, and Sinon. However, I encountered an issue when attempting to stub an object from a method: EvalError: Refused to evaluate a string as JavaScript because 'unsafe ...

`What is the best way to extract text and URLs from user input within a JSP page?`

I am having trouble with my programming skills while working on a web application using HTML and JSP pages. The goal of the application is to allow users to post content, but I am struggling to separate text from links within the textarea. Here is how the ...

Comparison of various approaches for invoking JavaScript/jQuery functions

Do the following examples have a performance variation? Example 1: $(window).on('resize', abc); function abc(){ //some abc code } Example 2: $(window).on('resize', function(){ //some abc code }); If so, what are the positives ...

What are the differences between jQuery, jQuery Mobile, and jQuery UI?

As someone fresh to web development, I find myself overwhelmed by the numerous frameworks available. I am interested in learning about the distinctions between these frameworks and how they can benefit my projects. Additionally, I am curious as to why jQu ...

Understanding Joi validation - setting a field as optional depending on the input received

I have been struggling to integrate the following joi validation. joiSchema = Joi.object().keys({ taskno: Joi.string().alphanum().required().uppercase().trim(), taskstatus: Joi.valid('G', 'C', 'I', 'S'), ...

Explore bar with search button

I'm facing an issue with the code I have for searching on my website. Currently, when a user fills in their search word and presses enter, it executes the command. However, I would like to only run the search script when the user clicks a button inste ...

What is the best way to remove bootstrap when transitioning to a new microfrontend?

Our team is facing an issue with styling when using a combination of React, Bootstrap, and Tailwind. The problem arises when linking our micro frontend to modules that use Tailwind, as the Bootstrap styles persist despite the change. Since both Tailwind an ...

Title Divider Right

I am looking to add a divider to the right of a section title on my webpage. Here is what I have tried: I attempted this code, but here is the result: Here is the code snippet: <h4 class="section-title">Lastest From Blog</h4> .section-title ...

Issue with mobile flipcard: Initial tap is unresponsive

Currently debugging the mobile version of a site built with Next.js. Encountering an issue where the first flip-card tapped on mobile refuses to flip properly. Instead, it selects the text on the opposite side of the card when tapped multiple times. The ...

Unable to retrieve the content of Material UI Textfield

I'm new to React and I need help with my login page that uses Firebase authentication. I have an input field to capture the user's contact information for validation, but I'm having trouble retrieving this data. I've tried various solut ...