Attempting to alter the animations depending on the color button that has been selected

Bootstrap radio buttons are being utilized.

I want the animation to change when one of these buttons is selected.

I am currently working on changing colors in JavaScript. I attempted to use a for each loop but encountered errors stating that it is not a function or undefined when trying to display a color.

const showcase = document.querySelector('.showcase');
const black = document.querySelector('#black');
const white = document.querySelector('#white');
const grey = document.querySelector('#grey');
const yellow = document.querySelector('#yellow');
const colorChoice = document.getElementById

let colors = [colorChoice];
console.log(colors);

// load events
loadEventListeners();
// size and color events
function loadEventListeners() {
  color.addEventListener('click', colorChange);
}

// color change
function colorChange(e) {
  colors.forEach(function(color) {

    if (color = black) {
      console.log(color)
      console.log('black')
      showcase.style.animation = 'blackjacket 6s infinite';
      showcase.style.animationTimingFunction = 'steps(1, end)';
    } else if (color = white) {

      console.log('white')
      showcase.style.animation = 'whitejacket 6s infinite';
      showcase.style.animationTimingFunction = 'steps(1, end)';
    } else if (color = grey) {
      console.log('grey')
      showcase.style.animation = 'greyjacket 6s infinite';
      showcase.style.animationTimingFunction = 'steps(1, end)';
    } else if (color = yellow) {
      console.log('yellow')
      showcase.style.animation = 'yellowjacket 6s infinite';
      showcase.style.animationTimingFunction = 'steps(1, end)';
    } else {}

    e.preventDefault();
  });
}
.showcase {
  width: 764px;
  height: 875px;
  margin: auto;
  background-size: contain;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  -webkit-animation: blackjacket 6s infinite;
  animation: blackjacket 6s infinite;
  -webkit-animation-timing-function: steps(1, end);
  animation-timing-function: steps(1, end);
}

@keyframes blackjacket {
  /* black */
  0% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/black%20jacket/front.webp')
  }
  33.3% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/black%20jacket/back.webp');
  }
  66.6% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/black%20jacket/side.webp');
  }
  100% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/black%20jacket/side.webp');
  }
}

@keyframes whitejacket {
  /* white */
  0% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/white%20jacket/front.webp')
  }
  33.3% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/white%20jacket/back.webp');
  }
  66.6% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/white%20jacket/side.webp');
  }
  100% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/white%20jacket/side.webp');
  }
}

@keyframes greyjacket {
  /* grey */
  0% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/grey%20jacket/front.webp')
  }
  33.3% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/grey%20jacket/back.webp');
  }
  66.6% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/grey%20jacket/side.webp');
  }
  100% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/grey%20jacket/side.webp');
  }
}

@keyframes yellowjacket {
  /* yellow*/
  0% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/yellow%20jacket/front.webp')
  }
  33.3% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/yellow%20jacket/back.webp');
  }
  66.6% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/yellow%20jacket/side.webp');
  }
  100% {
    background-image: url('https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/yellow%20jacket/side.webp');
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="colorchoice">
  <h2>Choose Color</h2>
  
  <div id="color">
    <div class="btn-group2" role="group2" aria-label="Basic radio toggle button group">
      <input type="radio" class="btn-check" name="colorradio" id="black" autocomplete="off">
      <label class="btn btn-secondary black" for="black"></label>

      <input type="radio" class="btn-check" name="colorradio" id="white" autocomplete="off">
      <label class="btn btn-secondary white" for="white"></label>

      <input type="radio" class="btn-check" name="colorradio" id="grey" autocomplete="off">
      <label class="btn btn-secondary grey" for="grey"></label>
      
      <input type="radio" class="btn-check" name="colorradio" id="yellow" autocomplete="off">
      <label class="btn btn-secondary yellow" for="yellow"></label>
    </div>

Answer №1

Below is an explanation with a functional CodePen example: https://codepen.io/STRINIX/pen/YzNzwyo

To initiate the change process, you'll need an event trigger. Using radio buttons, onClick event can be used along with specifying a value:

<input type="radio" class="btn-check" name="colorradio" id="black" autocomplete="off" onClick="colorChange()" value="blackjacket">
<label class="btn btn-secondary black" for="black"></label>

<input type="radio" class="btn-check" name="colorradio" id="white" autocomplete="off" onClick="colorChange()" value="whitejacket">
<label class="btn btn-secondary white" for="white"></label>

etc.

The javascript function for color change will resemble this:

function colorChange() {
    showcase.style.animation = document.querySelector('input[name="colorradio"]:checked').value + ' 6s infinite';
}

The queryselector identifies the active radio button based on its name and selection status, then retrieves its value.

Note that using a single equal sign (=) in if statements is incorrect syntax. It should be either two or three equal signs.

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

Saving user-generated inputs within a React.js component's state, focusing on securely handling passwords

Curious about forms in React.js? I don't have any issues, but I'm wondering if there are potential flaws in my approach. I've set up a basic form with two inputs for email and password: <input type="email" name="email" value= ...

Extract JSON content from an array's values containing underscores

I am currently working with an array of objects and need to implement a filter on it. The objects in the list contain an owner_id property within the JSON... Currently, I am looping through all the items in the array. However, I want to exclude those wher ...

Experiencing problems with the Datepicker and cloning functionality in JQuery?

This is the section of code responsible for cloning in JavaScript. $(document).on("click", ".add_income", function () { $('.incomes:last').clone(true).insertAfter('.incomes:last'); $(".incomes:last").find(".income_date_containe ...

The intersectsBox function unexpectedly returns true instead of false

I recently came across a tutorial on MDN that discussed the intersection of bounding boxes. Intrigued, I decided to try out the code snippet provided: const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3); const testBoxMaterial = new THREE.MeshBasicM ...

Tips on Implementing a CSS Variable in a React Component

Is there a way to use content variable with in-line styles in React? I am unsure of how to accomplish this. CSS3 .right::after, button::after { content: var(--content); display: block; position: absolute; white-space: nowrap; padding: 40px 40p ...

Having trouble with the functionality of the jQuery accordion feature

Below is the jQuery and HTML code I'm using for an accordion feature. I'm encountering an issue where the icons are not changing when the panels are collapsed or shown. When a panel header is clicked, it should become visible and collapse. In a ...

Popup showing values that are not defined

I've encountered an issue with tooltips on my bar graph. The tooltips should display the values of boarding and alightings corresponding to each stopname column, but I'm seeing undefined values like this Below is my code snippet: <!DOCTY ...

Press the Radio Button to automatically submit the form in ASP.Net Core

While working with ASP.Net Core, I encountered a scenario where I needed to update the page based on the radio button that a user clicks. I wanted the page to refresh automatically to display new data depending on the selected radio button. Would it be be ...

What is the best way to update a div element without the need for double clicking?

Let me explain this clearly. Currently, I have a table displaying in HTML when called. However, I want the table to disappear and show filtered results when someone enters a president's name and clicks on "Search for Presidents". I attempted using a c ...

Telegram Bot does not have the ability to be constructed in TypeScript

Why am I encountering this error message: TypeError: node_telegram_bot_api_1.default is not a constructor This is the TypeScript code snippet I have written: import * as dotenv from 'dotenv'; dotenv.config({ path: __dirname + '/.env&ap ...

having trouble with displaying the results on the webpage

I am facing an issue while trying to display the data fetched from the database: {"results": ["USA", "Canada"]} {"message":"Could not find any countries."} //else An error was encountered in the console: Uncaught TypeError: Cannot read property 'l ...

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

HTML/JavaScript: Embrace the Power of Dynamic Page

I have a unique element in my HTML code: <image src="http://..." style='...'> Using Python-Flask, I pass on a dynamic source address and save it as window.dynamicEmbedding. Now, during page load, I want to change the image's ...

Redux: One container for many components

I am new to React and Redux, and I am currently working on a project where I am unsure of the best practices and technical solutions. I am following Dan Abramov's definitions of "smart" and "dumb" components which can be found here. The component I a ...

What is the best approach to conceal elements from the main template in Meteor using a template event?

I have a main template along with two others that are displayed using Iron routing: <template name="main"> <div id="templateMain" name="templateMain"> <a href="nfnoscar">The Legend of NFN Oscar</a> <br/> <a h ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

Can you explain the variance between Angular 1.4.3's $http long form and shorthand methods?

Trying to decide between using the $http service in Angular the traditional way or the shortcut method – which one is better? Is there any impact on development, performance, or is it just a matter of personal preference? Personally, I lean towards the ...

Execute scroll to top animation but without utilizing $('html,body').animate({scrollTop: 0}, 'slow')

As someone who is just starting to explore jQuery, I hope you can bear with me. I've implemented this styling: html, body{ height: 100%; overflow: auto; } Along with this script: $(document).ready(function() { $('#guide-wrap'). ...