Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte.

Currently, I have set up the ASCII-Logo to include the necessary JavaScript code. The issue now is that I am unable to retrieve values from my Svelte "runtime" because the Javascript embedded in the Svelte store is completely separate from it.

For example:

// src/lib/stores.ts

const ascii =
`//||<button class="hiddenButton" onclick="{
          let elems = document.getElementsByClassName('hiddenImage');
          for (const elem of elems) {
              elem.classList.toggle('off')
          };
}">-.</button>||\\`;

Is there a way to access values from my Svelte TypeScript within the JavaScript being loaded from a Svelte store? Or should I consider splitting the ASCII instead?

The desired behavior I want to achieve is toggling between the ASCII and an image that replaces it while maintaining visibility. Currently, this is achieved by adding a CSS class with display: none.

  1. Toggling to reveal the image and hide the ASCII - works fine.
  2. Toggling to hide the image and show the ASCII - reveals the ASCII but doesn't toggle off the image.

Here's a simplified version of the code illustrating the problem.

// src/routes/+page.svelte

<script lang="ts">
    import { ascii } from '$lib/stores';

    $: off = true;

    let togglePicture = () => {
        let elems = document.getElementsByClassName('hiddenImage')!;
        for (const elem of elems) {
            elem.classList.toggle('off')
        }
        off = !off;
    };
</script>

<style>
    :global(.off) {
        display: none;
    }
</style>

<p class="hiddenImage">{@html ascii}</p><button on:click={togglePicture}>
<img src='/pics/favicons/dark-favicon.ico' alt="Dark Logo" class="pixelLogo hiddenImage{off === true ? " off" : null}">

Answer №1

It's best to steer clear of manipulating the DOM in this manner; using classes both in the markup and JavaScript can lead to confusion and errors.

If you need to display either ASCII or an image exclusively, you can easily manage this by toggling a flag with an #if/:else statement.

To toggle the flag on button click and ensure it persists, you'll need to store it somewhere accessible. You can delegate the logic handling through event bubbling, such as having a button within the ASCII text but handling its click in the Svelte code:

<script>
    const ascii = 'hello <button type=button data-button>b</button> world';

    let showImage = false;
    let container;

    function onClick(e) {
        const button = e.target.closest('[data-button]');
        if (button == null || container.contains(button) === false)
            return;

        showImage = !showImage;
    }
</script>

<div bind:this={container} class="container" on:click={onClick}>
    {#if showImage}
        <button type=button data-button>[Image here]</button>
    {:else}
        {@html ascii}
    {/if}
</div>

REPL

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

Getting the value of a JSON object in CodeIgniter can be easily achieved by using the appropriate

My current project involves using the codeigniter framework to build a website. I am making an AJAX request with jQuery to retrieve data from the server. I have experimented with two different methods of receiving the data: one in a PHP associative array a ...

Unexpected behavior with scrollTop

Note Reopening bounty as I forgot to award it last time. This question has already been answered by Master A.Woff. I am looking for a way to automatically scroll to a specific row when a user expands it, so that the content is immediately visible witho ...

Customizing Material UI CSS in Angular: A Guide

Recently, while working with the Mat-grid-tile tag, I noticed that it utilizes a css class called .mat-grid-tile-content, which you can see below. The issue I am encountering is that the content within the mat-grid-tile tag appears centered, rather than f ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

What is the best way to interpret a line break within a string variable in TypeScript?

Realtime Data base contains data with \n to indicate a new paragraph. However, when this data is retrieved and stored in a String variable, the website fails to interpret the \n as a paragraph break: https://i.stack.imgur.com/tKcjf.png This is ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

What is the best way to verify values in Vuejs based on their length?

<button type="submit" :disabled="(user.password && !$v.user.password.valid) || (user.confirmPassword && !$v.user.confirmPassword.sameAsPassword)">sda </button> By implementing a method based on character len ...

Accessing nested arrays and objects within JSON using Node.js

I'm in the process of developing an application that retrieves a JSON response from an API call using SONARQUBE. With node js, how can I extract the value of duplicated_lines from the following JSON object? I attempted the code below but it always r ...

Changed over to a promise-oriented database, causing my login feature to malfunction completely

Although I can successfully register, when I am redirected to my game route, all I see is a blank Error page with [object Object] on the screen. This message also appears in my console periodically. Initially, I suspected an issue related to socket.io, bu ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...

Module 'rxjs/internal/Observable' not found

When attempting to utilize the JwtHelperService module in my service, I encountered the following error: ERROR in node_modules/@auth0/angular-jwt/src/jwt.interceptor.d.ts(3,28): error TS2307: Cannot find module 'rxjs/internal/Observable'. In my ...

Error encountered when attempting to load files from the same domain due to CORS restrictions

I'm currently developing a website at and I am trying to load the content of an HTML file into an element. I have specified the element as $('.about-us-first-col') and I am loading the content using the code: $('.about-us-first-col&apo ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

The parent's setState does not trigger the child's componentWillReceiveProps

Within my application, there is a parent component and a child component with props connected to the parent's state. When I call setState in the parent component, the componentWillReceiveProps function of the child component does not always get trigg ...

"Function.click operates successfully when no arguments are given, but encounters issues when arguments are supplied

I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Unable to access external library using browserify and debowerify

I'm facing a dilemma with my current setup as I'm dealing with a headache. Here's how things are currently configured: Utilizing bower to acquire vendor libraries (specifically angular) Executing gulp tasks to run browserify Implementing d ...