Tips for managing click events in my class

I need assistance with dynamically adding and removing a class from a clicked element in AngularJS.

Here is an example of my code:

<li ng-repeat='test in tests' >
    <a href='' ng-click='pickTest($index, $event)'>{{test.title}}</a>
</li>

Here is my JavaScript:

 $scope.pickTest = function(index, event) {
     $(event.target).addClass('blur');
     //This code successfully adds the class 'blur' when an <a> tag is clicked
     //Now, I need to remove the class when another <a> tag is clicked
  };

Can anyone provide guidance on how to achieve this functionality?

Thank you!

Answer №1

To conditionally append a class based on a certain condition, you can utilize the ng-class directive. It is not recommended to use $index within an ng-repeat as it can cause issues when filters are applied. Instead, you can create two functions: isActive() to handle the ng-class directive and setActive() to designate the active item.

angular.module('app', [])

  .controller('Ctrl', function($scope) {
  
    var activeTest = {};
  
    $scope.tests = [{
      title: 'Test 1'
    }, {
      title: 'Test 2'
    }, {
      title: 'Test 3'
    }, {
      title: 'Test 4'
    }];
  
    $scope.setActive = function(test) {
      activeTest = test;
    };
  
    $scope.isActive = function(test) {
      return angular.equals(activeTest, test);
    };
  
  });
.blur {
  color: red;
}
<div ng-app="app" ng-controller="Ctrl">
  <ul>
    <li ng-repeat="test in tests">
      <a href="" ng-click="setActive(test)" ng-class="{blur: isActive(test)}">{{test.title}}</a>
    </li>      
  </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Answer №2

To implement blur effect using AngularJS, you can utilize ng-class as shown below:

<li ng-repeat='item in items' >
    <a ng-class={blur:blurActive} href='' ng-click='selectItem($index, $event); blurActive=true'>{{item.name}}</a>
</li>

It's worth noting that there is no need to explicitly set blurActive to true within your function. Due to the unique scope created by ng-repeat for each repeated item, you can toggle the active state within the same ng-click event after executing your function. This approach keeps the functionality separate from the styling logic.

Answer №3

Performing DOM manipulation within a controller is generally discouraged, a more angular way to accomplish this is by utilizing ng-class:-

   <li ng-repeat="test in tests">
       <a href="#" ng-click="pickTest($index, $event)" 
            ng-class="{'blur': opt.selectedIdx == $index}">{{test.title}}</a>
   </li>

and within your controller, simply:-

$scope.opt = {}; //Initialize a value in your controller

$scope.pickTest = function(index, $event) { 
     $event.preventDefault(); //If necessary
     $scope.opt.selectedIdx = index ; //Assign the current index here, you could also do this inline in the html, but it's usually better to have the logic in the controller
}

Plnkr

Answer №4

In order to properly assign the class to the element that is currently clicked, you should first remove the class blur from all other elements that have this class.

$scope.selectElement = function(index, event) {
     $('.blur').removeClass('blur');
     $(event.target).addClass('blur');
};

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

What is the reason behind the error "Uncaught SyntaxError: Malformed arrow function parameter list" when using "true && () => {}"?

When the code below is executed: true && () => {} it results in an error message stating: Uncaught SyntaxError: Malformed arrow function parameter list Why does this happen ? Update: I am aware that wrapping the function in parentheses reso ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

Filtering in AngularJS seems to only work in one direction

I am working on implementing two different ways of filtering data - one by clicking on letters and the other by typing in an input field. <body ng-controller="MainController"> <ul search-list=".letter" model="search"> <li class= ...

What is the reason that PHP has the ability to set Cookies but Local Storage does not?

Let's take a step back to the era of cookies, not too far back since they are considered old but still quite relevant. PHP allows you to set and read them even though they are a client-side technology; however, JavaScript can also be used completely o ...

Surprising outcomes encountered when playing audio with JavaScript

https://i.sstatic.net/1jz45.png I've been diving into learning JavaScript and decided to create a simple web page. This page, when Pikachu (image) is clicked, plays an audio file. Similarly, if the string "Pikachu" is typed into the form, it should ...

In React, ensure a component's state is preserved when the browser history changes

I recently developed a React application that features a classic layout with a left-side menu, title, footer, and main content section. The side menu includes navigation links structured using components such as <List>, <ListItem>, etc. from th ...

Extracting specific key-value pairs from JSON data

Working with JSON data, I encountered a need to pass only specific key-value pairs as data to a component. Initially, I resorted to using the delete method to remove unwanted key-value pairs, which did the job but left me feeling unsatisfied. What I truly ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Combining and organizing two sets of objects in Javascript

I am faced with a challenge of working with two arrays where each element receives a value based on its position within the array. Although both arrays contain the same elements, they are arranged differently. My goal is to calculate the value for each ele ...

Transform the text column into JSON format

We currently have a resource bundle/properties formatted as follows: [tag1] server1 server2 [tag2] server3 server4 [tag3] server5 server6 [No Software Installed] server7 [tag2] server8 [tag5] server9 [tag1] server10 server11 [tag3] server12 server13 serve ...

The functionality of the onclick button input is not functioning properly in the Google

Here is some JavaScript code: function doClick() { alert("clicked"); } Now, take a look at this HTML code: <div > <table border="2" cellspacing="0" cellpadding="0" class="TextFG" style="font-family:Arial; font-size:10pt;"> <tr> <t ...

ng-if used to reverse the order of ng-repeat rendering

Recently, I stumbled upon this code snippet and I'm wondering if the behavior exhibited is a bug or intended. To illustrate the problem, below is a snippet of the shared code used in both scenarios: <body ng-app="app" ng-controller="AppCtrl"> ...

I'm curious, what is the largest size the Three.js render canvas can be?

After setting the render canvas size to roughly 4000x4000px, everything appears fine. However, when testing sizes such as 5k, 6k, and 8k, it seems that part of the scene is being cropped in some way. View the image below for reference: https://i.sstatic.n ...

What are some alternative solutions when functional component props, state, or store are not being updated within a function?

Initially, I need to outline the goal. In React frontend, I display data that aligns with database rows and allow users to perform CRUD operations on them. However, in addition to actual database rows, I include dummy rows in the JSON sent to the frontend ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

Error: Webpack encountering reference errors when handling multiple entry points

Here is my setup in webpack.config.js: entry: { a:'./src/a.js', b:'./src/b.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].bundle.js' } The content of a.js includes: const ...