JavaScript programming does not rely on using the onclick method to style HTML elements

For a recent project, I was tasked with creating a toggle-style button setup for the challenge on CodePen. To achieve a 3D appearance for the button, I wrote some JavaScript code that utilized the onclick event.

var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
  if (on == false) {
    green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
    red.style.boxShadow = 'none'
    var on = true;
  }
}
var redOn = function() {
  if (on == true) {
    green.style.boxShadow = 'none'
    red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
    var on = false
  }
}

Here's the neatly bundled code snippet for your reference.

var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
  if (on == false) {
    green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
    red.style.boxShadow = 'none'
    var on = true;
  }
}
var redOn = function() {
  if (on == true) {
    green.style.boxShadow = 'none'
    red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
    var on = false
  }
}
.on {
  border-radius: 5px;
  background-color: lime;
  padding: 50px;
  border: none;
}
.off {
  border-radius: 5px;
  background-color: red;
  padding: 50px;
  border: none;
}
.switch {
  padding: 0;
  margin: 0;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div class="switch">
    <button class="on" id="on" onclick="greenOn()"></button>
    <button class="off" onclick="redOn()" id="off"></button>
  </div>
</body>

</html>

However, upon testing the implementation, nothing seems to happen when clicking the buttons. Any suggestions on how to fix this issue would be greatly appreciated!

Answer №1

Upon reviewing your code, I have identified two issues:

  1. The first problem lies in how you are setting the variable on within your function. By re-declaring it as var on = true and var on = false, you are creating a new variable with function scope instead of changing the globally declared one. To resolve this, update it to simply on = false and on = true within their respective functions.

  2. Additionally, the value that you are applying to the box-shadow property is not valid. Make sure to add a valid property value for the desired effect to take place.

var on = true;
const green = document.getElementById('on');
const red = document.getElementById('off');
var greenOn = function() {
  if (!on) {
    green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15)';
    red.style.boxShadow = 'none';
    on = true;
  }
}
var redOn = function() {
  if (on) {
    green.style.boxShadow = 'none';
    red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15)';
    on = false;
  }
}
.on {
  border-radius: 5px;
  background-color: lime;
  padding: 50px;
  border: none;
}
.off {
  border-radius: 5px;
  background-color: red;
  padding: 50px;
  border: none;
}
.switch {
  padding: 0;
  margin: 0;
}
<!DOCTYPE html> 
<html>

<head>
</head>

<body>
  <div class="switch">
    <button class="on" id="on" onclick="greenOn()"></button>
    <button class="off" onclick="redOn()" id="off"></button>
  </div>
</body>

</html>

Answer №2

Your code is experiencing issues due to re-declaring local variables with the same name as global variables:

var on = true
//...
var greenOn = function() {
  //...
  var on = true
}

When you redeclare on within the function, it creates a new local variable that shadows the global variable. This means the value is undefined and comparisons will fail.

if (on == true) {

To fix this issue, avoid redeclaring variables and simply assign their values instead:

if (on == true) {
  green.style.boxShadow = 'none'
  red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
  on = false 
}

Additionally, remember to always terminate your statements with semi-colons in JavaScript to prevent common bugs caused by omission.

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

Display Content in a DIV When Form Field is Unfocused

After hours of searching, I still haven't found a solution! I am trying to create a form field (text) where users can type in text. I want the text they enter to appear in a div on the screen either as they type or after they finish typing. Maybe thi ...

AngularJS: ng-show causing flickering issue upon page refresh

Recently, I encountered an issue with my code snippet: <body> <ng-view></ng-view> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/ ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

Building User-Friendly Tabs with Twitter Bootstrap: Add or Remove Tabs and Content on the Fly

Looking forward to any assistance or suggestions... I am utilizing Twitter Bootstrap tabs for organizing information on a form page. Each tab will contain a "contact form" where users can add multiple contacts before submitting the entire form. <div c ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

What sets apart using `: Interface` versus `as Interface` in Typescript?

I'm struggling to find the distinction between two similar lines of code due to uncertainty about what they are called. Consider the scenario where the following interface is defined: interface Person { name: string; age: number; } What exactly ...

What issue arises with arrays when programming in JavaScript?

Unusual scenario in JavaScript: var array1 = new Array(); var array2 = new Array(); array1 = [[1,2],[3,4]]; for (i = 0; i < array1.length; i++) { array2[i] = array1[i]; } alert(array2[1][0]); // -> 3 array1[1][0] = 10; alert(array2[1][0]); // -> ...

Do I require two bot logins for discord.js?

Working on my discord bot, I've been trying to incorporate a script from index.js. Should I also include bot.login at the end of cmdFunctions.js? Here is the content of index.js: const Discord = require('discord.js'); const bot = new Discor ...

Is it possible for two node scripts running on the same machine to interfere with each other's execution

In the scenario where a parent node file (such as an express server) spawns child nodes that execute computationally intense tasks, will these children cause blocking for the parent process? ...

Troubleshooting VueJs and vue-i18n issues

Currently, I am utilizing the Webpack CLI Template. As a next step, I proceed to install using the command npm install --save vue-i18n Within my main.js file, I undertake the necessary importation and configuration by setting the locale to "en" import ...

Ways to utilize this node.js module within a specific file

This is the third party node-js module I have created: var knox = require('knox') , Resource = require('deployd/lib/resource') , httpUtil = require('deployd/lib/util/http') , formidable = require('formidable') ...

Alter the content of an HTML page depending on whether a user is logged in two times on the same page

Currently, I am in the process of developing a login system for my website. Everything seems to be functioning correctly so far. However, I have an idea to enhance the user experience by displaying their name with a 'Manage' button next to it whe ...

How can I position the hyperlink inline with the font-awesome Icon?

Hey everyone, I'm having some trouble creating a top info bar in Bootstrap 4.1.3 with Font-awesome 5.5. I want to include essential details like phone number, email address, and social icons, but whenever I try to add a hyperlink after the icon, it dr ...

"Building a dynamic form with ReactJS, Redux Form, and Material UI - Implementing an

Currently working on a nested form framework that utilizes the redux form and material UI framework. The components have been developed up to this point - https://codesandbox.io/s/bold-sunset-uc4t5 My goal is to incorporate an autocomplete field into the ...

Adjusting image size to accommodate responsive column cell using CSS

I've been working on optimizing my mobile website using a responsive column layout. The challenge I'm facing is getting the images within each column to stretch to 100% width while automatically adjusting their height. I experimented with settin ...

What is the best way to adapt a wavetable for compatibility with the `OscillatorNode.setPeriodicWave` function?

I am exploring the use of a custom waveform with a WebAudio OscillatorNode. While I have basic programming skills, I am struggling with the mathematical aspects of audio synthesis. Waveforms are essentially functions, which means I can sample them. Howeve ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...

Pedestrian crossing Cordova experiences delayed response despite ontouchstart attempts to fix it

I have been experiencing a delay issue when using a CSS button with the ":active" pseudo-class on my phone. Every time I click the buttons, there is a noticeable delay before entering the active phase. Here is my CSS code: .btn {...} .btn:active{...} To ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...

What's the difference between using find_all on a bs4.element.ResultSet object and a list in Beautiful Soup

When I use the find_all method on a beautifulsoup object, it returns either an bs4.element.ResultSet object or a list. However, I am unable to directly apply the find_all method on the bs4.element.ResultSet object. One way to work around this is by loopin ...