Is it possible to adjust a CSS value once a JS value hits a specific threshold?

Currently, I am developing a web game where the website displays different emotions, including anger. I have successfully implemented the anger level internal coding and I am now focusing on adding a color-changing feature when the anger level reaches a specific value. My goal is to have the color shift slightly towards red when the anger level increases by 10. While I am not very experienced with CSS design, I usually incorporate existing designs that are available for use. Below, you can find the code that I am currently working with.

JavaScript Section

var anger = 0;
// Create a function that increments the anger level and updates the DOM
var incrementAndSet = function() {
anger = anger + 1;
document.getElementById("anger").innerHTML = "Anger level:" + anger;
console.log("Anger level:" + anger);
if (anger === 10) {
console.log("The site is very mad!!") 
bgcolor: #ffb347;
}
  if (anger === 20) {
console.log("The site is SUPER mad!!!")
bgcolor: #ff8243
}
  if (anger === 0) {
bgcolor: #69F7BE; 
}
}
// increment and set on click
document.getElementById('btn').onclick = incrementAndSet;

// initialize
incrementAndSet();

HTML Section

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" href="https://glitch.com/favicon.ico" />

    <title>Hello world!</title>
  
    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css" />

    <!-- import the webpage's javascript file -->
    <script src="/script.js" defer></script>
  </head>

  <body>
    <!-- this is the start of content -->
    <h1>
      Anger Minigame

    </h1>
    <p>
      This site is a game, meant for you to press the below button,
      making the site angrier and angrier.

      <button id="btn">Click Me</button>

      <div id='anger'>
      </div>

    </p>
  </body>

</html>

Answer №1

If you are looking to implement a dynamic CSS style within the DIV element with the id "anger", you can achieve this by referencing the DIV in your JavaScript code as shown below:

Your Updated Code

var anger = 0;
// Create a reusable function to increment and set the value within the DOM
var incrementAndSet = function() {
  anger = anger + 1;
  document.getElementById("anger").innerHTML = "Anger level: " + anger;
  console.log("Anger level: " + anger);
  
  if (anger === 10) {
    console.log("The site is very mad!!");
    // Apply style changes to the DIV with ID "anger"
    var el = document.getElementById('anger');
    el.style.backgroundColor = "#ffb347";
  }

  if (anger === 20) {
    console.log("The site is SUPER mad!!");
    // Apply style changes to the DIV with ID "anger"
    var el = document.getElementById('anger');
    el.style.backgroundColor = "#ff8243";
  }

  if (anger === 0) {
    // Apply style changes to the DIV with ID "anger"
    var el = document.getElementById('anger');
    el.style.backgroundColor = "#69F7BE";
  }

}
// Call the incrementAndSet function when the button is clicked
document.getElementById('btn').onclick = incrementAndSet;

// Initialize the function
incrementAndSet();

Answer №2

document.body.style.backgroundColor = '#ffb347'
signifies that the document.body element's style property, specifically the backgroundColor style, will be set to the color #ffb347

I also identified an error in your code where the increment started at 0 and then increased to 1 on the initial click, causing anger === 0 to never be achieved. Therefore, I adjusted it to commence at -1.

var anger = -1;
// Creating a function that can be reused for incrementing and setting in the DOM
var incrementAndSet = function() {
anger = anger + 1;
document.getElementById("anger").innerHTML = "Anger level:" + anger;
if (anger === 10) {
document.body.style.backgroundColor = '#ffb347'
}
  if (anger === 20) {
document.body.style.backgroundColor = '#ff8243'
}
  if (anger === 0) {
document.body.style.backgroundColor = '#69F7BE'
}
}
// Triggering increment and set function on click
document.getElementById('btn').onclick = incrementAndSet;

// Initializing the function
incrementAndSet();
<h1>
      Anger Minigame

    </h1>
    <p>
      Welcome to the anger minigame. Click the button below to increase the site's anger level.

      <button id="btn">Click Me</button>

      <div id='anger'>
      </div>

    </p>

Answer №3

Storing the background color in a variable outside of the if conditions and applying it after the if blocks will optimize your code.

Consider using the > operator instead of the === operator in your if statements.

Eliminating the final if statement that checks if anger is 0 can be achieved by assigning a default value to bg.

var anger = 0;
// Create a function that increments and sets the anger level
var incrementAndSet = function() {
  anger = anger + 1;
  document.getElementById("anger").innerHTML = "Anger level:" + anger;
  console.log("Anger level:" + anger);
  var bg = '#69F7BE';
  if (anger > 10) {
    console.log("The site is very mad!!")
    bg = '#ffb347';
  }
  if (anger > 20) {
    console.log("The site is SUPER mad!!!")
    bg = '#ff8243';
  }

  document.body.style.backgroundColor = bg;

}
// Call the function on button click
document.getElementById('btn').onclick = incrementAndSet;

// Initialize the function
incrementAndSet();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" href="https://glitch.com/favicon.ico" />

  <title>Hello world!</title>

  <!-- import the webpage's stylesheet -->
  <link rel="stylesheet" href="/style.css" />

  <!-- import the webpage's javascript file -->
  <script src="/script.js" defer></script>
</head>

<body>
  <!-- Game starts here -->
  <h1>
    Anger Minigame

  </h1>
  <p>
    This game allows you to make the site angrier by clicking the button below.

    <button id="btn">Click Me</button>

    <div id='anger'>
    </div>

  </p>
</body>

</html>

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

The function is attempting to access the 'lockDatabase' property of an undefined object, resulting in an error

I'm encountering an error due to the scope issue with 'this', and I'm struggling to find a solution. I attempted using the fat arrow, which solved the scope problem but created another issue where I lack a callback value that needs to b ...

Tips on personalizing the DateTimePicker component from Material-UI

I am currently working on customizing the DateTimePicker component provided by Material-UI. To access its documentation, please visit: One challenge I have encountered is the lack of styling information in the documentation. My goal is to change the main ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

What is the best way to ensure a div element on a printed page has a space between its bottom edge and the physical paper, as well as a space between its top

Within my div element lies a collection of other div elements. These elements contain lengthy text that may span multiple pages. I am attempting to print this text starting 50mm from the top edge of every physical paper, and stopping 20mm before the edge o ...

When I access the browser, it displays "???"" symbols instead of UTF-8 characters

When I view the website in my browser, it displays "???" instead of UTF-8 characters. How can I identify the cause and rectify this issue? Below is the content of the HTML file: <HTML> <title>Search Engine</title> <form ac ...

Transmitting PHP arrays to JavaScript through AJAX

I am struggling to retrieve an array from a SQL server using PHP and parse it to JavaScript using AJAX. Despite trying various solutions found through Google, I have been unable to successfully retrieve the array. Below is my PHP code: <?php inclu ...

Is a streamlined jQuery version of the Slider control designed specifically for mobile devices on the horizon?

Currently, I am developing a mobile web app and would like to incorporate the JQuery Slider control. http://docs.jquery.com/UI/Slider However, in order to do so, it seems that the entire JQuery core (29kb compressed & gzipped) is needed. My question ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

The code functions correctly when retrieving information from a file, however, encounters issues when retrieving data

While working on my React application, I encountered a situation where I needed to read the value for translation from a file stored in the public folder. The files were saved at https://i.sstatic.net/oWXCh.png However, due to the dynamic nature of our d ...

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

JS and MUI are combining forces to create a dynamic background change on the page when selecting items from a dropdown menu

I encountered an unusual issue on my website that appears to be related to the UI library I am using. Whenever I click on a select element, the background undergoes a slight change in width, causing the background image to flicker. Initially, I assumed thi ...

Having trouble with basic authorization for Facebook API using JavaScript?

I am having an issue with my source code. When I run it, I receive an alert that says "No Response" and then the Facebook page displays an error message stating "An error occurred with MYAPP. Please try again later" <div id="fb-root"></div> & ...

Creating a material texture with file api in three.js is a straightforward process

I have a vision to create a cutting-edge model browser that allows users to handpick models and textures themselves. In order to achieve this, I am utilizing the File API for smooth file handling. My approach involves using two separate file inputs for rec ...

Tips for setting the correct width for a DIV in Internet Explorer 8

I'm facing a little problem here. I'm trying to make a DIV 434 pixels wide in IE8, but for some reason it keeps getting rendered as 414 pixels. Can anyone tell me why it's cutting off 20 pixels? <html> <head> <style type= ...

"Help! I'm facing an issue with my PHP PDO insert statement

I've been working on developing a web application that allows users to create new projects, but I've hit a roadblock. For the past couple of days, I've been stuck on a particular issue related to the "New Project" button. When this button i ...

Creating a webpage with HTML through C++

I've been experimenting with posting an HTML page using C++. I created a class that utilizes sockets to implement TCP socketing. After checking, it seems like the issue lies in what I am sending: string s = "<!DOCTYPE html><html><head& ...

How can I handle pings in Discord using discord.js?

I've been working on a feature in my discord.js bot that responds to pings, but I'm running into issues. Even after trying <@BOTID> and @BOT#0000, the functionality is not behaving as expected. Here's the snippet of code I'm using ...