Issue with button toggle functionality in JavaScript not functioning correctly

I am fairly new to Vue and Javascript and I'm encountering an issue with two buttons that should change background colors when clicked. I've written some Javascript code to make them toggle, however, the problem is that while the Free button successfully changes the background color, the Paid button does not.

If anyone could provide assistance, it would be greatly appreciated.

function changeType(type) {
  var element = document.getElementById("myDIV");
  element.classList.toggle("active");
}

Here is the link to the Codepen showcasing what I am attempting to achieve:

https://codepen.io/Aadil_Hafesji/pen/bxZWLg

Thank you very much!!!

Answer №1

Update: Revised the function changeType to switch between two buttons. Additionally, included the class button to the buttons.

Ensure to include the event parameter in the function and toggle the class of event.target.

<button class="buttonCloserGreen button" onclick="changeType(event)">
   Free
</button>

<button class="buttonCloserBlue button" onclick="changeType(event)">
   Paid
</button>

Then modify the target element in changeType:

 function changeType(e) {
    let btns = document.getElementsByClassName('button')
    for(let i = 0; i < btns.length; i++) {
         btns[i].classList.remove("active")
    }
    e.target.classList.toggle("active");
 }

Demo

Answer №2

Here is an example of how you can achieve this:

<button class="greenButtonCloser" onclick="updateType(0)" id="mySelection0">
Free
</button>

<button class="blueButtonCloser" onclick="updateType(1)" id="mySelection1">
Paid
</button>

Using jQuery:

function updateType(type) {
      var item = document.getElementById("mySelection"+type);
      item.classList.toggle("activated");
    }

Answer №3

Including the entire element ensures you don't need to rely on the ID/Class for styling.

function modifyStyle(elem) {
  elem.classList.toggle("active");
}
.btnGreen{
    height: 45px;
    min-width: 200px;
    margin-bottom: 10px;
    border: 2px solid #53DD6C;
    border-radius: 8px;
    background-color: #ffffff;
    box-shadow: 4px 4px 20px 0 rgba(35, 31, 32, .05);
    transition: opacity 200ms ease;
    transition: transform 200ms cubic-bezier(.175, .885, .32, 1.275), opacity 200ms ease;
    font-family: Poppins;
    color: #53DD6C;
    font-size: 14px;
    line-height: 40px;
    font-weight: 700;
    text-align: center;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    cursor: pointer;
    outline: none;
}

.btnBlue{
    height: 45px;
    min-width: 200px;
    margin-bottom: 10px;
    border: 2px solid #0491F2;
    border-radius: 8px;
    background-color: #ffffff;
    box-shadow: 4px 4px 20px 0 rgba(35, 31, 32, .05);
    transition: opacity 200ms ease;
    transition: transform 200ms cubic-bezier(.175, .885, .32, 1.275), opacity 200ms ease;
    font-family: Poppins;
    color: #0491F2;
    font-size: 14px;
    line-height: 40px;
    font-weight: 700;
    text-align: center;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    cursor: pointer;
    outline: none;
}

.active{
  background-color: black;
}
<button class="btnGreen" onclick="modifyStyle(this)" id="myBtn1">
Free
</button>

<button class="btnBlue" onclick="modifyStyle(this)" id="myBtn2">
Paid
</button>

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

enclose code within square brackets

I have a shortcode function that currently works with or without square brackets. However, I would like it to only work with square brackets. shortcode (Current) itemText num="1" title="This is a title" shortcode (Desired) [itemText n ...

Arrange items in an array by two criteria

Sorting elements in a JavaScript array can be tricky, especially when trying to order them based on specific criteria like Ptr and Outputs values. In this case, the desired ordering is Node 0 -> Node 2 -> Node 1, where the Output of an element matche ...

Retrieve a URL from a string using Javascript

After hours of searching, I'm still stuck on this issue that seems like it could easily be solved with a quick Google search. Basically, I have this string that I'm ajaxing from another site: 'function onclick(event) { toFacebook("http://w ...

Bind Vue.js 2 component's data property to the very first instance of the component or to a single instance only

Seeking assistance. I am relatively new to Vue.js and require some guidance. Scenario: I have a component with BS modal inside, which is rendered in a loop and has multiple instances. Problem: The first rendered component receives its data from the p ...

Having trouble setting up Typescript in VisualStudio 2015 due to the error message "exports is not defined"? Need guidance on the correct setup?

I am new to TypeScript and I am currently learning about exports and imports in TypeScript However, as I started working on it, I encountered an error with exports Object.defineProperty(exports, "__esModule", { value: true }); The error message I receiv ...

Tips for resizing a tooltip using CSS

I am currently working on customizing tooltips and would like them to display right below the hover text in a responsive manner, with the ability to have multiline text. Instead of spreading horizontally, I want the tooltip to expand vertically based on th ...

Displaying outcomes in dialog box when button is pressed

I am working on a website where I want to enhance the user experience by displaying output in a dialogue box upon click. The current setup involves the user selecting a vendor and time duration, with the results appearing below the Submit button. However, ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

Is it possible to use ng-repeat on an array that contains data with inner arrays having similar key-value pairs, grouping them

I have a collection of data that includes sub-collections with a common key (TypeOfServiceAssigned:Array(2)) in both inner arrays. I am looking to use ng-repeat to group similar key-value pairs together and separate those that are different. For a clearer ...

Restrict the height of posts created in the summernote editor

My goal is to create a structured page application using summernote. When using summernote, a div with contenteditable=true is appended to the body to allow users to add content. However, I want to set a fixed height for this div so that users can only ent ...

difficulty arises when attempting to invoke a viewmodel from another viewmodel inside a ko.computed function

Is it possible to have two view model functions in my JavaScript where one references the other? I am encountering an error with this setup. Here are my view models: var userViewModel = function (data) { var _self = this; _self.ID = ko.obs ...

Instructions for resolving the Sys.ArgumentTypeException error: The object of type 'Object' cannot be converted to type 'Function'

I encountered a specific error in my JavaScript function that I'm struggling to resolve. Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function'. Parameter name ...

Making HTTP requests with axios in Node.js based on multiple conditions

I'm facing an issue with making get calls using axios to both activeURl and inactiveURl. The goal is to handle error messages from the activeUrl call by checking data from the inactiveUrl. However, I keep receiving error messages for the inactiveURL e ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

How to identify a button click on an HTML page within an Android WebView

When using my Android app, I encounter an issue with a webview that contains a form and a submit button. The button code snippet is as follows: <button role="button" class="btn ng-binding" ng-click="actions.collect()" tooltip="default" title="Check f ...

Ways to position a button at the bottom of a Bootstrap card

In the card layout, I am struggling to position the red button at the bottom of the column despite using margin auto. Can anyone provide a solution for this issue? Thank you in advance! <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a ...

Utilizing the Power of Graphql with NuxtJs

Exploring the integration of GraphQL with NuxtJs. I am facing a challenge as NuxtJs does not offer an option to have a provider in the root element. How can I properly inject the apolloProvider into the root Vue element? Goal: https://github.com/Akryum ...

Angular NgClass Issue (Unable to bind to 'ngClass' as it is not recognized as a property of 'a')

Hi there! I am relatively new to using Angular and I am currently facing an issue while attempting to dynamically add a Bootstrap class to my HTML based on the active tab. Unfortunately, I am encountering an error. Can anyone provide assistance? The error ...

The outcome of my function designed to calculate the highest possible profit using k transactions is a null array

I have developed a custom function to calculate the maximum profit from a series of stock transactions given a specific number of transactions allowed. Each transaction involves buying at a low price and selling at a higher price, with the rule that you ...

The ideal way to efficiently await retrieved data in vue.js to ensure smooth integration in another function

Is there a way to properly handle the successful fetch event before executing the loadMarkers() method? I keep encountering an error because monitorsData.monitors is undefined. I attempted using await with fetch but I'm unsure of the correct usage. ...