Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what's happening. I am currently working with Svelte and am still inexperienced, hence the code quality is comparable to a PowerPoint presentation.

<script lang="ts">
  export let name;

  function onTopBarBtnClick(tab) {
        let tabButton = document.getElementsByClassName('topbarbtn ' + tab)[0]
        tabButton.classList.add('selected')
  }
</script>

<main>
  <nav class='topbar'>
    <label class="websitenameinfo">{name}</label>

    <button on:click={() => onTopBarBtnClick('1')} class="topbarbtn 1">Servers</button>
    <button on:click={() => onTopBarBtnClick('2')} class="topbarbtn 2">Events</button>
    <button on:click={() => onTopBarBtnClick('3')} class="topbarbtn 3">Store</button>
    <button on:click={() => onTopBarBtnClick('4')} class="topbarbtn 4">Info</button>
  </nav>
</main>

<style>
    .topbar {
        position: absolute;
        width: 100vw;
        height: 8vh;
        top: 0vh;
        left: 0vw;
        background-color: #1c1c1c;
        box-shadow: 1vh 1vh 2.8vh rgba(28, 28, 28, 0.8);
    }
    .websitenameinfo {
        position: absolute;
        top: 1vh;
        left: 1vw;
        text-transform: uppercase;
        font-family: Tahoma;
        font-size: 4.7vh;
        background: -webkit-linear-gradient(#2071cd, #0ac7ba);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      text-shadow: 0px 0px 3vh #579dffb3;
        font-weight: 800;
    }
    .topbarbtn {
        width: 10.1vw;
        height: 8vh;
        float: right;
        border-radius: 0px;
        background: -webkit-linear-gradient(#20cd31, #0ac7ba);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      text-shadow: 0px 0px 3vh #15ffbd5e,
                                 0px 0px 1.5vh #1573ff66;
        font-weight: 600;
        font-family: Tahoma;
        font-size: 3.8vh;
        border-image: linear-gradient();
        border-width: 0px;
        border-left-width: 0.1vw;
        border-color: rgb(45, 45, 45);
        color: rgb(52, 52, 52);
        vertical-align: top;
    transition: all 0.3s cubic-bezier(0.075, 0.82, 0.3, 1);
    }
    .selected {
            border-color: #0af05e;
            width: 15vw;
            border-left-width: 0.27vw;
            text-shadow: 0px 0px 3vh #6fffd6da, 0px 0px 1.6vh #84ff106d;
    }
</style>

After exhausting all my options available online, I still couldn't resolve the issue. My anticipation was for the buttons to widen and the left border color to switch to green upon clicking. However, it seems that nothing happens whatsoever when I click on them. It may be a problem with how I'm adding 'selected' to the class list, although I can't say for certain.

Answer №1

When working with Svelte, it's best to steer clear of directly manipulating the DOM through methods like

document.getElementsByClassName()
. Instead, utilize Svelte's reactive capabilities to handle state management and apply dynamic classes based on that state. Here's a sample implementation:

<script lang="ts">
  import { onMount } from 'svelte';

  let selectedTab = null;

  function onTopBarBtnClick(tab) {
    selectedTab = tab;
  }

  // Define a function to remove the 'selected' class when the component mounts
  onMount(() => {
    return () => {
      selectedTab = null;
    };
  });
</script>

<main>
  <nav class='topbar'>
    <label class="websitenameinfo">{name}</label>

    <button on:click={() => onTopBarBtnClick('1')} class:selected={'1' === selectedTab} class="topbarbtn">Servers</button>
    <button on:click={() => onTopBarBtnClick('2')} class:selected={'2' === selectedTab} class="topbarbtn">Events</button>
    <button on:click={() => onTopBarBtnClick('3')} class:selected={'3' === selectedTab} class="topbarbtn">Store</button>
    <button on:click={() => onTopBarBtnClick('4')} class:selected={'4' === selectedTab} class="topbarbtn">Info</button>
  </nav>
</main>

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

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Exploring the AngularJS global Date timezone offset

I want to display dates based on the users' time zones. I am hoping that Angular provides a way to globally configure the Date filter for this purpose. Doing it manually for each case doesn't seem right to me. My timestamps are already passed t ...

Scrolling text box utilizing Jquery

Currently, I am utilizing a scrolling box that functions well * view here * under normal circumstances. However, when there is an extensive amount of content below it, such as: <article class="content"> ...

Is it considered poor practice to employ setTimeout to ensure that a function is executed after the useEffect hook has run?

Let's imagine I have the following code snippet: const [test, setTest] = useState(); const [test2, setTest2] = useState(); useEffect(() => { setTest2(undefined); }, [test]); const calledFunction => () { setTest(whatever); setTest2(this ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Tips for passing down CSS styles through Less stylesheets

In an effort to create a legend below a <table> that matches the colors defined in Bootstrap stylesheets, I am struggling with the following: .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot ...

Create a custom navigation bar using PlayFramework for a unique video streaming website

Attempting to create a dynamic navigation bar in Play using the code below in my main.scala.html file: @(title: String)(content: Html) <!DOCTYPE html> <html lang="en"> <head> <title>@title</title> <li ...

Align images to the left in Typora for a cleaner look

Typora typically aligns all images in the center by default. https://i.stack.imgur.com/TrqIM.png In my search through the github.css, I was unable to locate any instances of img. $ grep img "/Users/me/Library/Application Support/abnerworks.Typora/themes ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

Place a small image within a list item to ensure it matches the height of the list element

I need help aligning images to the right within list elements. The images are squares with equal height and width, and I want them to fit snugly within the height of the list element on the right side. My HTML code is quite simple for now (see example bel ...

Positioning of dropdown in Material UI select component

Unfortunately, I am encountering an issue with the Menuprops attribute and cannot seem to adjust the position of the drop-down box. Despite following the instructions from other similar queries, the desired outcome remains unachieved. My goal is to have t ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

Passing Down Instance Methods Using Static References in JavaScript/TypeScript

✋ Exploring the concept of access modifiers from TypeScript, how can we make it relevant for JavaScript developers as well? Let's consider a scenario where a parent class defines necessary members and a shared method: // ParentClass.js export defaul ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Tips for incorporating a smooth fade in and out effect into images within a Bootstrap 5 carousel

I'm currently working with a Bootstrap 5 carousel and trying to implement a transition effect where clicking the "next" arrow will smoothly fade out the current image before fading in the next one. This is necessary because the images in my carousel v ...

Deserialization does not support the use of Type System.Collections.Generic.IDictionary for an array

An issue might arise when trying to call a page method using a manually created JQuery.ajax request. The deserialization process is handled by .NET and not within the user's code. Javascript: MyParam = []; ... $.ajax({ type: 'POST', ...

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...