Refreshed the page following a setAttribute function call in Javascript

I have successfully implemented a function to switch between light and dark mode on my webpage using VueJS. However, I am facing an issue with the code:

    <a @click="toggleTheme"  class="switch-mode" href>
      <div class="switch-mode-btn">

      </div>
    </a>

toggleTheme() {
    let currentTheme = localStorage.getItem('theme');
    currentTheme == 'darkMode' ? currentTheme = '' : currentTheme = 'darkMode';

    document.documentElement.setAttribute('data-theme', currentTheme);
    localStorage.setItem('theme', currentTheme);
}
mounted() {
    let localTheme = localStorage.getItem('theme');
    document.documentElement.setAttribute('data-theme', localTheme);
},

css

:root {

    /* LIGHT MODE */
    --background-color: #fcfcfc;
    --text-color: rgba(17, 24, 39);
    /* END LIGHT MODE */
}

[data-theme="darkMode"] {
    /* DARK MODE */
    --background-color: rgba(17, 24, 39);
    --text-color: #fcfcfc;
    /* END DARK MODE */
}

Whenever I click on the toggleTheme function, my page reloads. Is there a way to make this dynamic without refreshing the page? Any help would be greatly appreciated.

Thank you

Answer №1

Solution A :

add the .prevent modifier when calling your method

<a @click.prevent="toggleTheme"  class="switch-mode">
   <div class="switch-mode-btn">

   </div>
</a>

for more information on modifiers, refer to : Event Modifiers

Solution B :

simply delete the href attribute from your <a> tag

Answer №2

Delete the href attribute within the a tag to prevent the constant reloading caused by the empty href.

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

Automating image uploads with Selenium and Python even when the element appears hidden

Recently, I've encountered an issue while trying to upload photos using Selenium with Python. The input element appears to be hidden on the page, causing errors when using the .sendkeys method. Here is the HTML code for the input element: <div d ...

Using Vue with Webpack and PapaParse for efficient data parsing

I have encountered an issue while trying to implement PapaParse's worker option () with Vue's webpack template (https://github.com/vuejs-templates/webpack). The error message I'm receiving is: Uncaught ReferenceError: window is not #defi ...

Display or conceal specific fields depending on the selection from a dropdown menu

I'm currently experimenting with using JavaScript and/or jQuery to dynamically hide specific HTML elements based on the selection in a drop down menu. Here is what my page setup looks like: [Drop down menu] [text field 1] [text field 2] [text field ...

Utilizing AJAX to Invoke a Method in a CS Page: A Step-By-

I am trying to utilize AJAX to call a method in my CS page. Below is the design code I am using: <!-- Name --> <input type="text" name="name" id="name" required="required" class="form" placeholder="Name" /> <!-- Email --> <input type= ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

Hold tight for the response from the AngularJS factory request

In my Rails application, I am incorporating Angular. The code snippet below shows an API request being made and the code in the .run function being executed. Sometimes, the API response is still pending when the code is executed. This leads to issues with ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

Is it possible that only one number is printed when document.getElementById("demo").innerHTML = Math.ceil((Math.random()*10)-1); is executed?

How come the code document.getElementById(“demo”).innerHTML = Math.ceil((Math.random()*10)-1); is only displaying one number? function myFunction() { var bbb = document.getElementById("ilgis").value; for (i = 0; i <= bbb; i++) { //docum ...

Protected login form

I've designed a login form that prompts users to enter their username and password in order to access index.php. Additionally, I have authenticate.php set up, which is required by index.php to prevent unauthorized access. However, I'm struggling ...

In Groovy (or Java), learn the techniques to properly escape double quotes within HTML inner text while leaving attributes untouched

I am currently utilizing an HTML rendering engine that is based on Groovy within a Web Content Management (WCM) system. I have encountered a scenario where the user inputs rich text content into a form based on TinyMCE, which appears as follows: <p> ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

When loading HTML using JavaScript, the CSS within the HTML is not properly processing. Leveraging Bootstrap 5 might help resolve

Currently utilizing bootstrap 5 for my project. I have a setup in index.html where I am loading the contents of nav.html using JavaScript. However, I am facing an issue wherein the CSS styling for the navbar is not being applied when loaded via JS. Strange ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

Data assigned to KendoUI chart must have keys that do not consist of numbers

When I input the following simple data into a KendoUI chart, the chart displays the data correctly. var data = [ {"state":"NY","abc":12312}, {"state":"AZ","abc":12312}, {"state":"CA","abc":12312}, ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

"Troubleshooting the issue of consistently receiving null values when uploading files with

I'm facing an issue with uploading a file using jQuery AJAX. Although I can see all the details of the file object such as its name and size, when I check the console with formdata.get("files"), the context.request.files size always shows zero. It see ...

Enable Vue2 Select Component to accept a variety of arrays for selection choices

I am currently developing a customizable Select component that can be used with any Array provided as options. It is working well when the object properties in the array have the same names bound in the component. However, if an array of objects with diff ...

Utilizing React for handling data exchange between child and parent components

I am still learning about React and material-ui, and I am exploring how to pass data from a child component to a parent component to update the parent state. Currently, when I try to update the state with a new date, it is being logged in the console but t ...