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

Struggling with transferring form input data to a different file using JavaScript, Node.js, React.js, and Next.js

I've been struggling with writing form input to a separate file in JavaScript. I created a demo repo to showcase the issue I'm facing. Check it out here: https://github.com/projectmikey/projectmikey-cant-write-to-api-dir-stackoverflow Locally, t ...

Experiencing issues calling a function in Vue.js while working with the SDK JavaScript?

When attempting to integrate the JavaScript SDK into Vuejs by utilizing a Facebook login button, I encountered an issue: <template> <div> <div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="login_with" d ...

Keeping the Drawer open in Material-UI: What you need to know!

I am looking to create a collapsible sidebar feature in Material-UI where only the icons are displayed when collapsed. I have successfully implemented the Mini Variant Drawer for the basic sidebar functionality, but I'm facing an issue with maintainin ...

Display a confirmation dialog using AngularConfirm after a function in AngularJS has finished executing

Trying to figure out how to update the $ngConfirm box after a function is done. When submit is clicked, a spinning cog appears: $scope.inProgress = function(){ $ngConfirm({ theme: 'modern', icon: "fa fa-cog fa-spin fa-.5x ...

Verify whether the username is present in the Firebase database using JavaScript

Using Firebase Function, I have created a function that allows users to complete their profile by adding an entry to the Firebase Realtime Database. Here is an example of how the database structure looks: { users: { AeknQrtMIyPpC4EQDPNQYvQUxCA3: ...

Incorporate a link to an image following a click event toggle using Jquery

I managed to create a code snippet that toggles between two images when clicked, thanks to some assistance from stackoverflow. However, I am now looking to add a link to the second image that redirects users to another webpage, like The App Store. My ques ...

Contrasting "npm run dev" with "npm start"

I have just started learning about Node and AngularJS. Could someone explain the distinction between npm run dev and npm start commands in the node terminal? ...

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

If I don't utilize dependency injection in Angular, it prompts me for arguments

Attempting to implement a service like this but encountering some issues translateService = new TranslateService(); An error message pops up stating that there are 9 missing arguments. However, when I modify it to look like this constructor(private trans ...

Update the button functionality according to the button's unique identifier

I am trying to dynamically change the button's redirect link based on its ID in my NEXT.JS project, but as a newcomer to this framework, I am unsure of how to accomplish it. I understand that this modification should be done after rendering, possibly ...

Initializing a table with data will only function properly when a breakpoint is set

Using the bootstrap-table library, I initialize a table with data fetched via ajax request. var arr = []; var getRows = function () { $.ajax({ type: "GET", url: hostUrl, contentType: "app ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Ways to automatically update ng-class based on changes in ng-model value

I am working on a code where I need to add classes to the 'label' based on whether the input box is empty or not. To achieve this, I am checking if the input box is null and adding classes accordingly. <div class="col-md-12"> <input ...

What is the process by which node.js synchronously delivers a response to a REST web service?

Sorry if this question seems obvious! I'm struggling to grasp how node.js handles requests from the browser. I've looked at tutorials online where express.js was used to create the server-side code with node.js. Routes were then set up using prom ...

Is there a way to automatically remove flash messages in AngularJS after a certain period

For controlling the timing of clearing my FlashService message, I attempted to implement a timeout feature. However, it seems to function more like a delay. FlashService.Success(("Removed Successfully"), false); In this instance, I have used false as a c ...

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...

What is the reason that my "width: auto" property is not properly adjusting to the content's width?

My css code, width: auto is causing issues with the content width I am a beginner in HTML, CSS, and JavaScript, seeking help with my website. I have multiple divs within a section element, but the section's width is not adjusting to fit the divs prop ...

React, handling various router navigations

I have set up a BrowserRouter to serve /, /login, and /logout on my website. Once logged in, users can access an app with a consistent navbar on every page and dynamic content that holds data/functionality within the "Main" template component, which utiliz ...

Generating dynamic content

I require assistance with a programming issue. I am working with two separate components: Stage and Executor. Within the Stage component, I am attempting to create new elements based on input parameters, while in the Executor component, I set these paramet ...

Content will be displayed below the background image

Help Needed: Content Going Over Background Image Hey there! I'm having a bit of trouble with my home page design. I have a full-width background image, but the content isn't displaying below it like I want it to. Instead, it's showing over ...