Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red.

When the Today button is clicked, the background color changes to blue and the text color changes to white.

The same design should apply to the Tomorrow button when clicked, while the Today button returns to its default colors. Here is the code:

<div class="row" style="height: 52px;">
    <div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
      <span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
    </div>

    <div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">
          <span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
        </div>
    </div>

Controller for ng-click on both buttons :

$scope.GetDetails = function(){

     $ionicLoading.hide();
   $scope.orders.length = 0

    MydeliveryFactory.save($scope.orderInfo, function(response){
     var AllOrderValues = response.allorders;
        for (var i = AllOrderValues.length - 1; i >= 0; i--) {
            if(AllOrderValues[i].dateAdded == todaydate && AllOrderValues[i].monthAdded == todayMonth ) {
              $scope.orders.push(AllOrderValues[i]);
               $ionicLoading.hide();
              console.log($scope.orders);

            } 
          } 
        $window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));

    });
  }

$scope.GetTomorrowDetails = function(){
     $ionicLoading.show();
       $scope.orders.length = 0
    MydeliveryFactory.save($scope.orderInfo, function(response){
    var Allvalues = response.allorders;
        for (var i = Allvalues.length - 1; i >= 0; i--) {
            if(Allvalues[i].dateAdded == tomorrowdate && Allvalues[i].monthAdded == tomorrowMonth) {
              $scope.orders.push(Allvalues[i]);
                $ionicLoading.hide();
              console.log($scope.orders);
            } 
          } 
        $window.localStorage.setItem("MyDeliverYOrders", JSON.stringify($scope.orders));

    });
  }

Answer №1

To switch classes, utilize ng-class and $scopes.

I included

ng-class="{'active':active.today}"
in a button, which means that the active class will be applied when active.today is evaluated as true, and removed when it's false. The same applies for the "tomorrow" button.

In the JavaScript function, the code simply toggles the $scope between true and false.

angular.module('myApp', []).controller('myCtrl', function($scope) {
  $scope.active = {};
  $scope.GetDetails = function() {
    $scope.active.tomorrow = false;
    $scope.active.today = true;
  }

  $scope.GetTomorrowDetails = function() {
    $scope.active.today = false;
    $scope.active.tomorrow = true;
  }
});
.active {
  background: blue;
  color: #fff!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl" class="row" style="height: 52px;">
  <div class="col col-50" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails()" id="1">
    <span class="assertive" ng-class="{'active':active.today}" style="margin: 0px;color: #B90143;">TODAY</span>
  </div>

  <div class="col col-50" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails()">

    <span class="assertive" ng-class="{'active':active.tomorrow}" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
  </div>
</div>

Answer №2

If you want to dynamically change the class of your buttons, take a look at ngClass in AngularJS.

Your button HTML could be structured like this:

<button ng-class="[btn, btn-primary, {today: active-class}]" ng-click="GetDetails()">Today</button>
<button ng-class="[btn, btn-primary, {!today: active-class}]" ng-click="GetTomorrowDetails()">Tomorrow</button>

Your controller may look something like this:

$scope.today = true;

$scope.GetDetails = function() {
    $scope.today = true;
}

$scope.GetTomorrowDetails = function() {
    $scope.today = false;
}

Answer №3

To make your buttons consistent, add a shared class and apply the default CSS styles.

<div class="row" style="height: 52px;">
    <div class="btn col col-50 common-btn-style" style="border-right: 1px #ccc solid; padding-top: 17px; text-align: center;" ng-click="GetDetails($event)" id="1">
        <span class="assertive" style="margin: 0px;color: #B90143;">TODAY</span>
    </div>
    <div class="btn col col-50 common-btn-style" style="padding-top: 17px;text-align: center;" ng-click="GetTomorrowDetails($event)">
        <span class="assertive" style="margin: 0px;color: #B90143; width: 100%;">TOMORROW</span>
    </div>
</div>

.common-btn-style {
  background-color: white;
  color: red;
}

Update your Controller to manage the button click events:

$scope.GetDetails = function(event) {
  $scope.defaultColors();
  event.target.style.backgroundColor = "blue";
  event.target.style.color = "white";
};

$scope.GetTomorrowDetails = function(event) {
  $scope.defaultColors();
  event.target.style.backgroundColor = "blue";
  event.target.style.color = "white";
};

$scope.defaultColors = function() {
  [].slice.call(document.getElementsByClassName("common-btn-style")).forEach(function(el, i) {
      el.style.backgroundColor = "white";
      el.style.color = "red";
  });
};

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

Google Chart Fails to Display

I am encountering an issue while attempting to integrate a Google chart into my project. The page fails to load, rendering a blank screen. Initially, the page displays correctly for a brief moment after loading and then suddenly turns blank, becoming unres ...

Integrating Dialogflow with a Heroku JavaScript application

After extensive research, I delved into the realm of integrating DialogFlow requests with a webhook hosted on platforms like Heroku. With both Heroku and nodeJS impeccably installed on my system, I diligently followed the heroku tutorial to kickstart the p ...

Customize your Bootstrap 4 navbar to align on the right with a button that remains visible on mobile devices

I'm working on setting up a navbar with three elements. I want to have a left-aligned brand, a group of right-aligned links that will collapse on smaller screens, and an additional button that stays visible at all times. To achieve the alignment of t ...

Learn how to leverage the drag and drop directive in AngularJS for your web

I integrated drag and drop functionality into my project using: https://github.com/marceljuenemann/angular-drag-and-drop-lists This is how I implemented it: <div ng-repeat="list in lists"> <div style="float: left; margin-left: 5px;"> ...

Placing the Controller outside of the View will help improve the

Currently, I am utilizing RequireJS in conjunction with AngularJS and my goal is to assign a controller to the body element. The key components include the elements nav and .container. While .container automatically updates with the route, I am looking t ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading. My current setup looks like this: var n = 100; var myData = []; function loadMovies(n){ // async ajax requests // add items to ...

Retrieving information from an AJAX callback

Is there a way to extract the URLs from PHP data? Here is an example script that may help you achieve this: PHP $query = 'SELECT * FROM picture LIMIT 3'; $result = mysql_query($query); while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) { ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

Contrasting the purpose of a function in pure JavaScript versus a function within the scope of an Angular controller

Could someone clarify the distinction between declaring these two functions in an angular controller? function demo() { }; scope.demo = function() { }; Are these two functions similar in perf ...

Implementing CSS styles based on the count of elements

Within my react js project There is a particular block that may contain either one or two elements, depending on the runtime conditions. For instance: Scenario 1: (two groups are present) <div class='menu-list'> <div class='g ...

What is the reason for the React component being rendered four times?

My React component is fetching data from Firestore and storing it in the items array. However, I am encountering an issue where the menus variable contains three empty arrays that are being rendered on the page. Initially, I used an async function to fetc ...

What is the best way to display form input fields depending on the selected value?

I've been struggling with a seemingly simple issue that I can't seem to find the right solution for, even after scouring Google. I have a form field for input and a select field with various values, including an "Other" option. Here's what ...

Looking for a way to ensure a div reaches 100% height within a specified area without exceeding the boundaries of the body?

I am working with jQuery mobile and have specific requirements for my project: The main content will be a large graphic that needs to fill the entire page, with both horizontal and vertical scrolling if necessary. The header should remain fixed at the to ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

Using websockets in a React client application

Attempting to establish a connection with a backend layer running on localhost, here is the provided source code: const { createServer } = require("http"); const cors = require("cors"); const photos = require("./photos"); const app = require("express")( ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...