Creating a function to dynamically assign a class to multiple buttons when a specific button is clicked

I am working on a nuxt.js web application where I have both static and dynamic buttons. When the static button is clicked, I want to add a specific class to each dynamic button.

Currently, the code I have is able to add the class to the first dynamic button, but it doesn't work on the rest of them. The class gets added dynamically after the first button.

<button  @click="scrollToDiv()" class="btn btn-block btn-primary py-2 text-center rounded" style="background: #1f7ae0; border: #1f7ae0;">

Here are the multiple dynamic buttons:

<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>

Below is the script that handles adding the class:

scrollToDiv() {
    document.getElementById('pricing').scrollIntoView({
        behavior: 'smooth',
    })
    var enroll = document.getElementById('enroll')
    enroll.classList.add('glow')
    var scrollTimeout
    clearTimeout(scrollTimeout)
    scrollTimeout = setTimeout(function () {
        enroll.classList.remove('glow')
    }, 2000)
}

The goal is to apply dynamic CSS to each dynamic button when the static button is clicked:

.glow {
    color: #fff;
    background: linear-gradient(40deg, #2031ffa1, #05ff75cf) !important;
    border-radius: 12px !important;
    box-shadow: 5px 5px #ff922e !important;
  }

Answer №1

Since you utilized nuxt.js, I am assuming you are familiar with vue.js.

  1. Include a toggle value in the data section
  data () {
    return {
      ...
      glow: false,
      ...
    }
  }
  1. Add class binding to each dynamic button. Use :class="{ glow }" attribute to bind the glow class name when the glow data is true.
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
  1. Only manipulate the glow data. This will affect each button's class name.
scrollToDiv() {
  this.glow = true
  setTimeout(() => {
      this.glow = false
  }, 2000)
}
  1. Define a timeout ID in data (similar to a global variable in the component). In your initial code, the timeout id scrollTimeout was a local variable in scrollToDiv, making clearTimeout meaningless. Every execution of scrollToDiv creates a new scrollTimenout in the function scope.
  data () {
    return {
      ...
      glow: false,
      timer: null,
      ...
    }
  },
...
  methods: {
    ...
    scrollToDiv() {
      this.glow = true
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
          this.glow = false
      }, 2000)
    }
  }
...

Answer №2

Each element's ID should be unique, which means that when using getElementById, you will only get the first element that matches. One suggestion is to assign the same class to all three buttons and then use

getElementsByClassName(className)
. This will give you an HTMLCollection that allows you to loop through each element. Here's an example:

activateAnimation() {
  document.getElementById('features').scrollIntoView({
    behavior: 'smooth',
  })
  var elements = document.getElementsByClassName('btn-class')
  for(let e of elements) e.classList.add('animate')
  var animationTimeout
  clearTimeout(animationTimeout)
  animationTimeout = setTimeout(function () {
    for(let e of elements) e.classList.remove('animate')
  }, 2000)
}

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

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

looking to save a service or factory as a variable

I seem to be at a standstill when it comes to finding a solution for my mvc.NET / angularjs project. So far, I believe I've done a good job abstracting the view to use a controller that matches the type name of the specific controller.cs class: < ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...

Symfony's DataTables is encountering an issue with the JSON response, showing

I have encountered an issue while trying to fetch data from a response within my template table (using DataTables). The error message I receive is as follows: DataTables warning: table id=example - Invalid JSON response. For more information about this ...

Using a combination of ASP.NET webpage and JavaScript, a dynamic webpage with a repe

I am new to using VB and integrating JavaScript. I have a simple question, but I'm having trouble figuring it out for some reason. I am struggling to properly construct an IF-statement. Can you please help me? I have searched and googled, but have no ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Error in connecting Node.js with mongoose

I am working on a Node.js project that involves a MongoDB database and uses Mongoose schema. The project consists of three files: index.js, users.js, and db.js. However, I am encountering an issue when trying to connect to MongoDB using Mongoose. Below is ...

Deleting files in a mongodb collection using node.js

As a beginner in mongoDB and Node.js, bear with me if the following code is not flawless. The task at hand is to delete a document from a collection using its _id. The deletion works fine in the mongo shell, but there seems to be an issue when executing t ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

`Struggling with managing callbacks, handling errors, and working with MongoDB`

I recently revamped my code for an application that handles adding companies to a database. In the past, my code was messy and unorganized, so I decided to structure it properly by introducing routes, a controller, and a data access object. Here is how my ...

What is the best way to showcase a JSON object in an attractive format on a webpage?

Similar Question: JavaScript data formatting/pretty printer var theobject_string = '{...}'; // I have a JSON object as a string. Is there a way to present this string in a visually appealing manner on an HTML webpage? I would like the ...

Can you explain the variance between using 'npm i' and 'npm install'?

Can you explain the distinction between running npm i and npm install? Both commands are used to install all node Modules listed in the package.json file. While the purpose of both commands is clear - to install modules, there may be subtle differences be ...

"Type Error: Attempting to assign a value to a const variable by declaring it as let while importing a variable from another file

Within JavaScript(Node.JS), I created a config.js file as shown below to export a variable named "name": Config.js export let name = "ayush"; Then, I imported the variable "name" into the index.js file index.js import {name} from "./config.js"; name = ...

Guide to adding a new font to your Ember project

I am currently in the process of developing a website utilizing the MEEN Stack framework (Mongo, Ember, Express, Node). One challenge I am encountering is importing the Lato font family into my project to serve as the main font for the entire site. Despite ...

What is the best way to retrieve and utilize various data from a JSON object? Is creating an array necessary for this task?

As a novice, I am currently utilizing $.get to fetch data from a REST API, the JSON response looks like this: [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, ...

Update: When a variable changes during onUploadProgress in Vue.js, the DOM is not re

Having a bit of an issue here. I'm working on an app where users can upload images using axios. In order to enhance the user experience, I'm trying to implement a loading bar. Here's what it looks like: <div class="loadingbox" :style="{ ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Performing a repeated action to choose each item from a dropdown menu

I attempted to streamline the process by creating id tags for each dropdown and implementing a loop to select each manufacturer without having to write an extensive amount of code. However, I encountered difficulties and was unable to find a solution. The ...

Add a file to the input field using JavaScript and the input type="file"

I am facing the challenge of sending a file (up to a few MB) generated by JavaScript to a server using POST (not ajax POST). I am wondering how I can add a file to an input type="file" using JavaScript. After checking Pre-Populate HTML form file input, it ...