Use Angular to change the style of multiple element groups at the same time when hovering

When hovering over an element with a common attribute, such as a class name, I want to change the style of all elements that share that attribute. Achieving this effect is simple with jQuery:

$(function() {
   $('.bookId4').hover( function(){
      $(this).css('background-color', '#F00');
   },
   function(){
      $(this).css('background-color', '#000');
   });
});

However, I am unsure how to implement this feature using Angular. In my scenario, the elements with the class .bookId4 are dynamically generated through an Angular AJAX call, so I am looking for a way to create the hover effect in Angular as well. Thank you!

EDIT

To elaborate further, multiple divs will be created via an AJAX call, and these divs within the same group will share the same class. Here is the HTML code snippet:

<div class="bookId{{ privateTour.booking.id }}"> <!-- Wrapper for hover effect -->

When hovering over one div, I want ALL divs (not just the hovered one) with the same class or another shared value to exhibit the hover effect. Ideally, Angular should search the entire page for all divs with a certain class name and apply the desired style to achieve this, instead of having to manually generate CSS for each class, which may not even work effectively.

Answer №1

To achieve this functionality, you can utilize the ng-mouseenter and ng-mouseleave directives. Below is a basic code snippet that you can customize to fit your specific needs:

<!doctype html>
<html lang="en>
<head>
  <meta charset="UTF-8>
  <title>Sample - sample-sample89-production</title>

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

</head>
<body ng-app="">
<h1 ng-style="myStyle" ng-mouseenter="myStyle={'background-color':'blue'}"" ng-mouseleave="myStyle={'background-color':'none'}"">Hello World</h1>
</body>
</html>

Answer №2

If you want a quick solution for hover effects, consider using a simple CSS approach like this:

.bookId4:hover {
    background-color: '#F00';
}

No need to involve Angular or jQuery for this task! :-)

Answer №4

Implement the use of ng-class by creating a single scope variable that is initially set to false. Update this variable to true or false based on mouseEnter or mouseLeave events.

<style>
    .bookId4{color: red;}
</style>        
<span  ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()"  ng-class="{ 'bookId4' : ctrl.ishovered==true }">Something 1</span>
        <span  ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()" ng-class="{ 'bookId4' : ctrl.ishovered==true }">Something 2</span>
        <span  ng-mouseenter="ctrl.hovered()" ng-mouseout="ctrl.nothovered()" ng-class="{ 'bookId4' : ctrl.ishovered==true }">Something 3</span>

            _this.ishovered = false;    
            _this.hovered = function(){
                _this.ishovered = true;
            }
            _this.nothovered = function(){
                _this.ishovered = false;
            }

Answer №5

After experimenting with different solutions, I discovered that using an ng-class condition was the most effective way to highlight a specific group based on a variable. Initially, I encountered issues with only the hovered div being highlighted, prompting me to revise my approach.

<div ng-class="hovering == privateTour.booking.id ? 'hl' : ''" ng-mouseenter="setHover(privateTour.booking.id)" ng-mouseleave="setHover(0)"> <!-- Wrapper for hover effect -->

To ensure a global highlighting effect, I modified the code to send signals to a variable using a function. The updated code for the div wrappers is as follows:

<div ng-class="hovering == privateTour.booking.id ? 'hl' : ''" ng-mouseenter="setHover(privateTour.booking.id)" ng-mouseleave="setHover(0)"> <!-- Wrapper for hover effect -->

I then implemented a simple function in the scope:

$scope.setHover = function(bookId) {
    $scope.hovering = bookId;
};

Additionally, here is the style definition for the highlight class .hl:

.hl {
background-color: red;
}

Special thanks to everyone who suggested using ng-mouseenter and ng-mouseleave!

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 best way to ensure that when a div is opened, the information to the right does not get pushed down?

I have a functioning menu bar, but when it expands, the content below is pushed down even though it should not be affected. How can I adjust my code to prevent this issue? View my website here: <div id="menu_wrapper"> <div id="menu"> &l ...

Event that signifies a change in the global state of the Angular 2 router

Is there a universal event that can be utilized for state change/start across all components, similar to the Component Lifecycle Hooks ? For example, in UI-router: $rootScope.$on("$stateChangeStart", function() {}) ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Is there a way to eliminate the whitespace beneath the "Brilliant" division?

[Screenshot of white space under div] [1]: https://i.sstatic.net/cO7TV.jpg I'm having trouble figuring out why there is visible white space here. As a coding beginner, I would really appreciate any assistance. I've tried searching for the soluti ...

What is the best way to display changing data in a React component?

Having some trouble with printing data based on the length of an array. Here is my attempted solution, but unfortunately, it's not working as expected. I believe the issue lies in the cb function within the forEach loop. Below is the code snippet: fun ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...

The Element should take up the entire page with the exception of a 20px margin

I am struggling to create an element that covers the entire page except for a 20px margin on all sides. I have tried implementing a solution using this code, which works in webkit browsers and Firefox but seems to have issues with Internet Explorer (10) an ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

Suggestions for updating the 'begin' and 'finish' variables transmitted through ajax on fullcalendar?

Shown below is the URL to request JSON data via Ajax: '/php/get-events.php?start=2015-05-31&end=2015-06-07&_=1433154089490'. This query will fetch JSON data from 2015-05-31 to 2015-06-07. However, I am looking to retrieve data over a ...

Teaching you how to incorporate empty spaces and punctuation within JOI

How can I modify Joi to permit spaces/whitespaces in a title field within a form? Scheduled to work with Jude tomorrow. I want to allow entries like: Morningwalk Currently, only the second example is passing validation. Below is my existing Joi val ...

What is the method for eliminating quotes from a URL?

Changing the URL: history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14="'+urldates+'"&usp-custom-8="'+title+'"'); After making changes, it s ...

How to arrange a collection of objects in JavaScript

I am facing a challenge with sorting the array based on the address._id field of each object. Despite attempting to use the lodash orderby function, I have not been able to achieve the desired outcome. [{ rider_ids: '5b7116ea3dead9870b828a1a& ...

Using Twig: Transfer the content of a textfield as a parameter in the routing

I have a task of redirecting to another page while passing along the value from a textfield. Here is my current code: {% extends "base.html.twig" %} {% block body %} <button onclick="host()">Host the session</button> <button onclic ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...

Async function captures error being thrown

I am looking to implement an async function in place of returning a promise. However, I've run into an issue with rejecting using error throwing: async function asyncOperation() { throw new Error("Terminate this application."); } (async () => { ...

Tips for keeping a div fixed at a specific scroll level

Is there a way to keep a specific side div fixed at a particular scroll level, similar to the "How to format" bar on the right side of the Stack Overflow ask question page? You can see it when you try asking a question. How can this be achieved - with CS ...

Update the image source every few seconds

I am attempting to show the same image in both gif (animated) and jpeg formats. I am updating the src every few seconds. After checking in the developer tools, it seems that the src has been modified, but the gif does not appear to be animating. setInter ...

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

Warning thrown by jsHint: 'Firebase' is not defined

How can I properly define Firebase to stop JSHint from beeping? My code is functioning fine... it's just JSHint that's annoying app.js angular .module('morningharwoodApp', [ 'firebase', 'ngAnimate', & ...