Is there a way to adjust the text color based on whether a value is negative?

I am currently developing a web application that performs addition operations on integers. Within this application, I have implemented two functions named num1() and num2() to retrieve the integers provided by the user for calculation. My objective is to modify the color of the output text based on whether the sum of the integers is negative. How can I achieve this using JavaScript exclusively?

While I have come across numerous jQuery solutions, my preference is to accomplish this task solely with JavaScript.

function addIntegers() {
        var sum = num1() + num2();
        
        if(sum < 0) {
            document.getElementById('display').innerHTML = "Result: " + sum;
        } else {
            document.getElementById('display').innerHTML = "Result: " + sum;
        }
    }

Answer №1

When working with DOM objects, you can utilize the .style object to customize various properties. Specifically, if you need to modify the text color, you would target the color property within your function as shown below:

function calculateSum() {
    var total = getFirstNumber() + getSecondNumber();
    var element = document.getElementById('result');
    element.innerHTML = "Total: " + total; 
    if (total < 0)
        element.style.color = 'red'
    else 
        element.style.color = 'green'
}

To optimize your code, I transformed the targeted element into an object so that repetitive calls to getElementById are avoided. Additionally, since the sum always needs to be displayed, it is no longer necessary to include it in the if statement; focus solely on changing the color based on the value.

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

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

JavaScript Character Set on the Dynamic Page in Delphi

Within my Delphi application, I am dynamically generating HTML content. Displaying UTF-8 encoded strings in the webpage body is not an issue for me as I use HTMLEscape to encode regular strings (ensuring all strings in the list are properly escaped). The ...

What are the recommended methods or examples for implementing a scheduling calendar using JavaScript?

Here's a question that may be open to interpretation, and a red warning banner suggests it might be closed, but I'm not sure where else to turn for answers. I need an extremely lightweight display-only scheduling calendar for my application. Ess ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

Tips for incorporating a value within the AngularJS select function

Having an issue with passing a list value in the html select method using AngularJS. Here is my code: app.js $scope.subcategory = function() { var query = "SELECT unit FROM Length;"; $cordovaSQLite.execute(db, query).then(function(res) { ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

Utilizing Jquery on the client side in conjunction with a Node.js server

I am using nodejs within a docker-compose container to create a local web app. My goal is to use jquery on the client-side to load an HTML file into a div, but I'm encountering issues with it not working properly. Both the initial index.html and the n ...

Tips for transferring information from a form to your email address

I am trying to find a way to automatically send form data to my email without the user having to open their inbox. I attempted to use the "mailto" function but it didn't work as desired, still opening the email box. Here is the script I tried: functio ...

Right-click context menu not working properly with Internet Explorer

Seeking assistance with extracting the URL and title of a website using JavaScript. The script is stored in a .HTM file accessed through the registry editor at file://C:\Users\lala\script.htm Below is the script: <script type="text/java ...

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...

Arrange the JSONB data type with sequelize literal in your order

My current approach involves querying for all items using the following structure: const filteredItems = await allItems.findAll({ where: conditions, include: associations, order: sortingCriteria, limit: limit, o ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Using Jquery to enhance navigation tabs with pointers

I am facing an issue where the class .hover and .over are added to the entire list whenever I mouseover any list item. I understand that this is happening due to my jQuery code, but I would like to find a way for jQuery to only add the class to the specifi ...

The LinkedIn API encountered an error when attempting to retrieve historical follower data, resulting in a HTTP

I've scoured the depths of the internet in search of a solution to my problem, but none seem to fit what I need. My goal is to retrieve historical follower data from LinkedIn's API using this call: ${companyId}/historical-follow-statistics?time- ...

The effect of iPad screen orientation on CSS styling

Exploring orientation testing using CSS for iPad. Below is the code snippet from the CSS file: @media only screen and (device-width:768px) and(orientation:portrait) { body { background: green; } } @media only screen and (device-width:768px) and(orient ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

Trigger an event prior to the loading of a div

I have been working on a jQuery code that needs to run just before a specific div is displayed on the page. Take a look at the snippet below as an example of what I am trying to achieve: $(document).ready(function(){ $('.article').on('m ...

Executing functions within express - a mystery

I am struggling with a back-end JavaScript issue in Express. For some reason, when I call my function, it is returning undefined. Here's how it looks: // express route structure: exports.check = function(req, res) { // check if the username is prese ...