Having difficulty altering the color of certain text using JavaScript

Below is a function that I need help with. It's a simple function that changes the text color to green when the eventStatus shows as Active:

function() {
    var diff, status;
    diff = moment().diff(date, 'days')
    if (diff > 0) {
      status = 'Ended';
    }
    if (diff < 0) {
      status = 'Pending';
    }
    if (diff === 0) {

      status = 'Active';


        //status.style.color = "#132111"

        // document.getElementById('greenActive').style.color = "green"
    }
    return status;
  }

UPDATE HTML:

<td id = "status-column"  >
      <span id="greenActive" >{{eventStatus}}</span>  
   </td>

I tried using both 'status.style.color' and 'getElementById', but the text wasn't showing up at all.

Can you pinpoint where I went wrong?

Your assistance is greatly appreciated!

Answer №1

Update:

The code is functioning correctly, but it's important to ensure that you execute the code after the DOM has fully loaded.

(function() {
    var diff, status;
    diff = 0
    if (diff > 0) {
      status = 'Ended';
    }
    if (diff < 0) {
      status = 'Pending';
    }
    if (diff === 0) {

      status = 'Active';

        document.getElementById('greenActive').style.color = "green"
    }
    return status;
  })();
  <td id = "status-column"  >
      <span id="greenActive" >{{eventStatus}}</span>  
   </td>

Make sure the document is fully loaded and that the DOM element you are trying to modify is accessible before calling your function. You can view a demonstration of JavaScript modifying text color at this link

Answer №2

Here is a JavaScript function that determines the status of an event based on the difference in days:

function checkEventStatus() {
  var diff, status, statusColor = '';
  diff = moment().diff(date, 'days');
  
  if (diff > 0) {
    status = 'Ended';
  }
  
  if (diff < 0) {
    status = 'Pending';
  }
  
  if (diff === 0) {
    status = 'Active';
    statusColor = '#5CB85C';
  }

  return '<div style="background-color:' + statusColor + '">' + status + '</div>';
}

Below is the HTML code snippet that displays the event status using this function:

<td id="status-column">
  <span id="greenActive">{{eventStatus}}</span>  
</td>

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

Unable to amend or remove fields within a JSON object

Typically, my process would include the following steps: var res = {}; res = { _id: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5327362027132736202736217d303c3e">[email protected]</a>', ...

Convert Screen Coordinates to World Coordinates with ThreeJS

While many people are interested in converting camera position to screen position, my question is how to achieve the opposite. Currently, I am trying to set the position of the "door" as a percentage of the screen, with the necessary calculations already ...

encountering an unforeseen error during an ajax request

Currently, I am utilizing an ajax request in my Chrome extension to connect with an API and retrieve data. Initially, there were CORS errors which I managed to resolve. However, I am now encountering some ambiguous errors where the links are getting mixed ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

What can be done to address the narrowing of the left div element as the right div's child elements grow in size?

Utilizing the power of flexbox, I have organized the UI into left and right panels. The child elements within the right panel are stacked vertically by utilizing the white-space: nowrap; CSS property. However, there seems to be an issue where increasing t ...

Angular continually monitors changes for dom-to-image and generates countless renders

I am trying to implement a feature in my Angular 4 application where child-components render wallpapers for themselves using dom-to-image-more. The issue arises when I try to dynamically render these child-components using *ngFor. The parent component h ...

"Troubleshooting: The ExitApp Function in PhoneGap's navigator.app is not

I'm currently exploring Phonegap to create a new app, but for some reason the navigator.app.exitApp()? command doesn't seem to be functioning as expected. This project marks my debut into the realm of hybrid apps. My primary focus is on Android ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

Update the :hover effect on elements within a pseudo element

Within our menu, I have a main menu item and its sub-items change color to orange on hover. Additionally, I've implemented some JavaScript to create a toggle for collapsing/expanding the menu. However, due to the positioning of the span element over t ...

Trigger multiple toggles with a single @click event

I am working with a single HTML element and I want to implement three different toggles using just one @click event: Toggle the visibility of a nested <p> Toggle an <i> element Toggle the background color of the parent box (.faq-box) W ...

Utilizing Jquery to Attach Events to Multiple Instances Across a Webpage

I have successfully created a script that works perfectly, but now I am facing an issue with replicating it on a page. The jQuery script manipulates textarea boxes based on button clicks, however, I require each textarea box to have its own set of buttons. ...

jQuery fails to update the CSS3 animation speed dynamically in IE10

I am currently working on a side project that involves using moving divs with @keyframes and CSS3's animation property. Initially, I faced difficulties in getting this to work smoothly on webkit browsers due to issues with transform3d. However, after ...

Tailored Bootstrap form styles for different screen sizes

Can someone please help me understand how to create a custom Bootstrap class that applies to a specific breakpoint? I've tried using w-md-50, w-sm-100, w-lg-75 for a form, but it doesn't seem to be working for the targeted breakpoint. Are there a ...

Is it possible to find a match by searching through multiple arrays for a corresponding variable name?

Hi there, I'm currently working on a function that triggers an alert if the name of an array of images matches the data attribute of the selected element. This is just a test phase before proceeding with my main project, but I've hit a roadblock. ...

Everything runs smoothly when initiating the API call through npm start, but unexpectedly crashes upon attempting to

Here is an API call located at http://localhost:9000/testAPI. Within the bin/www file: var port = normalizePort(process.env.PORT || '9000'); app.set('port', port); Inside the routes/index.js file: var express = require('express&a ...

Having trouble locating the "forgot account" link below the password input field

While practicing website layout design, I attempted to emulate the Facebook landing page. Everything was going smoothly until I encountered an issue with the positioning of the “forgot account” link under the password input field. Strangely, it seems t ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

Verify the overlay for numerous divs problem

Checking for overlaying divs using these functions: function checkCollision($div1, $div2) { var x1 = $div1.offset().left; var y1 = $div1.offset().top; var h1 = $div1.outerHeight(true); var w1 = $div1.outerWidth(true); var b1 = y1 + h1; var r1 ...

Interactive PayPal quick checkout feature

Currently, I am in the process of developing an online store for a personal project and this piece of code is extracted from my application. <div class="row"> <script src="https://www.paypalobjects.com/api/checkout.js"></script> {{#e ...