When selected, apply the active class to one element until another element is selected. Upon selecting the second element, switch the active class to the second element and remove it from

I am working on maintaining the "active" class on a clicked widget tile until another sibling is clicked, regardless of any other click action on the page. While this functionality works within the widget itself, if the user clicks elsewhere on the page, the active state is lost. How can I prevent this from happening?

For the tile:

<div ng-click="tile.clickButton(0)">
, I have experimented with:

ng-class="clickButton ? 'active' : '' "

as well as

ng-class="{'active': clickButton = true}"

and

ng-class="showRespectiveEvent ? 'active' : '' "

(where `showRespectiveEvent` triggers visibility of another widget on the page)

I have also tried:

resource for adding and removing classes in AngularJS using ng-click

approaches for adding multiple functions in one ng-click event

methods to set the active class on ng-click

despite trying various solutions, nothing seems to be effective...

Below is the simplified code for displaying widgets on the page (stripped down for privacy reasons):

<div >
   <div>
       <ng-include src="'Widget Tile Page'"></ng-include>
   </div>

<!-- This is the widget that the tiles hide/show when clicked -->
   <div class="row">
        <div ng-if="thisPageCtrl.showRespectiveEvent"></div>
   </div>
</div>

// Code for Tile Widget Page:

<div ng-controller="tile as wtl">
    <div class="row>
       <div class="tile" ng-click="wtl.clickButton(0)">
          <div>{{wtl.someButtons[0].title}}</div>
          <div>{{wtl.someButtons[0].data}}</div>
       </div>
    </div>
</div>

<script>
$scope.clickButton = clickButton 

function clickButton(iIndex) {
        var btn = $scope.someButtons[iIndex];
        $rootScope.$emit("highLight", btn);
    }
</script>    

// CSS:

.tile {
color: purple;
border: 1px solid purple;
}

.tile.active {
font-weight: 900;
color: deeppink;
border: 1px solid deeppink
}

The desired outcome is for the active class to persist unless another tile within the widget is clicked. Currently, clicking elsewhere on the page removes the active class.

Answer №1

Let's set you on the right path with this solution:

(function() {
  var app = angular.module('tileApp', []);

  app.controller('TileController', function() {
    this.activeTile = null;
    this.someButtons = [{
      title: 'title1',
      data: 'data1',
    }, {
      title: 'title2',
      data: 'data2',
    }, {
      title: 'title3',
      data: 'data3',
    }];

    this.clickButton = function(index) {
      this.activeTile = index;
    }
  });
})();
.tileContainer {
   display: grid;
   gap: 20px;
   grid-template-columns: repeat(3, 1fr);
}

.tile {
   color: purple;
   border: 1px solid purple;
   padding: 20px;
   cursor: pointer;
}

.tile.active {
  font-weight: 900;
  color: deeppink;
  border: 1px solid deeppink;
  background: pink;
}
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
  </head>
  <body ng-app="tileApp">
    <center><h1>Active Tile</h1></center>
    <div class="tileContainer" ng-controller="TileController as tile">
        <div class="tile" ng-click="tile.clickButton($index)" ng-repeat="button in tile.someButtons" ng-class="tile.activeTile === $index ? 'active' : ''">
           <div>{{button.title}}</div>
           <div>{{button.data}}</div>
        </div>
      </div>
  </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

Extract the entire div including all its elements and then transmit it using the PHP mail function

Currently, I am developing a feature that allows users to send an email. The email should include only one div from the page which contains elements added using the jQuery drag and clone function. I am unsure how to copy the entire div along with its child ...

Generate a jQuery iframe once more by requesting it

How can I use jQuery to create an iframe tag and set it as the only content of a specific div? If the target div already has content, I want to replace it with a dynamically created iframe tag. This is what I have attempted so far: $(".someClass").click ...

Interactive div with dynamically generated click event

I need to add an onclick event to a button that is being generated dynamically via ajax. How can I achieve this? This is the code responsible for generating the content. When we click on an item, I want a popup window to appear. function retrieveTableDat ...

What is the best way to utilize variables in order to style this image inside a selector?

Struggling with adding dynamic styling to an image inserted into a div through a selector. Despite successful testing of the style changes, I am stuck on how to assign variable values for the properties. Various syntax attempts have failed so far. functi ...

Materialize card resizing feature allows for easy adjustment of card

I am attempting to utilize 3 cards to showcase the most recent news on my site. It looks great on a wide screen like this https://i.sstatic.net/50Dbm.png However, when I resize the page, the content overflows from the card. This is the code snippet: < ...

Unable to resize the image due to CSS limitations

My pursuit for an answer has hit a dead end... I'm currently attempting to insert images as preview images for a link; the images and link become visible with a javascript command triggered by pressing an icon. However, despite my efforts, the image r ...

Issues with Vue-select dropdown functionality are causing inefficiencies

I am utilizing vue-select to generate a standard drop-down menu. However, it comes with a search bar by default that I do not need and prefer to keep it simple. I attempted to hide the search bar by using "display: none" which made it disappear. This is t ...

The box shadow feature does not function properly when the position is set to sticky

Applying position sticky to th and td in the example below seems to be causing issues with the box shadow not working. Can anyone provide insights on why this is happening? <div class="overflow-x-auto lg:overflow-visible"> <div> <t ...

Ways to display all image sources in React

I have an object containing product information, which includes answers with associated photos. I attempted to create a method that iterates through the images array and generates image tags with the source link, but for some reason, the images are not d ...

Modifying the `font-family` attribute in Angular Chart.js

Is there a way to customize the font-family in Angular Chart along with setting a custom font for labels? I'd like to know how to modify them according to my design needs. ...

Menu with dropdown navigation

Looking to create a dynamic and responsive navbar menu with items and subitems on my website. Bootstrap has proven to be challenging when adding submenus. Are there any tools, frameworks, codes or plugins that could assist me in achieving this? It's ...

Optimizing Window Width with React.js and CSS

I'm currently in the process of building a responsive website with react. I am utilizing CSS stylesheets for styling and have used @media queries to ensure responsiveness. However, I've encountered an issue while testing in Chrome where the elem ...

Expanding the dimensions of $state.store.object within a vue.js application

As I delve into learning Vue.js, I've noticed that the application I'm currently developing fetches data from a database and then organizes it into a list before binding and displaying it on the page. Here's a snippet of the code where this ...

Setting a Value?

Within the services.js/Cordova file, I am encountering an issue with the following code: .factory('GCs', ['$http', function($http) { var obj= {}; $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} ) ...

"Unfortunately, the yeoman generator-material-app seems to be malfunctioning at

While delving into studying the Yeoman and testing a generator equipment-app from https://github.com/michaelkrone/generator-material-app, I encountered a problem. During the application process, an error appeared in the browser console: TypeError: cssClas ...

moment.js is unable to extract the time information from a timestamp

I'm having trouble converting a timestamp using moment.js from a json data set. When I try to use moment.format('MMMM Do YYYY, H:mm:ss'), the output is showing something like May 25th 2361, 0:00:00 for the timestamp 12351223423. This seems t ...

The process of Single Sign-On (SSO) - a comprehensive look into its

Looking to integrate Single Sign-On (SSO) into all future php/angular applications. Aware of services like Auth0 and oauth.io that act as intermediaries for SSO apps, along with OAuth 1.0/2.0 protocols. Unclear on the complete process flow for creating a c ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Transferring a PHP variable via a URL

I'm having a bit of difficulty passing the value of a variable named artID as part of an href link. It seems like where I place this variable impacts whether or not the link actually works. If it's outside of the PHP tags, the link breaks, but if ...

How should one correctly utilize this extension within AngularJS code?

I've recently started using a framework known as Radiant UI, which allows me to incorporate HTML5 UI elements into Unreal Engine 4. As I work on this project, I decided to enhance my knowledge of modern JavaScript by developing the UI in AngularJS. A ...