Guide to implementing a hover effect with background image on a div using AngularJS

Is there a way to switch the background image on a div when hovering over it without changing the class? I am using a bound property to populate the information and struggling to find a solution. While I have found a method using jQuery, it doesn't feel like the most Angular-friendly approach. Any suggestions?

Answer №1

Approach #1: No need for a controller, everything is handled in the template.

<div ng-init="bg = ''" 
    ng-mouseenter="bg = 'http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100'" 
    ng-mouseleave="bg = ''" 
    style="background-image: url({{bg}});">
</div>

Approach #2: Utilizing variables to store the values (requires a controller)

<div ng-mouseenter="bg = imageOn" 
    ng-mouseleave="bg = imageOff" 
    style="background-image: url({{bg1}});">
</div>

Controller:

function myCtrl($scope){
    $scope.bg1 = "" // default image set here.
    $scope.imageOn = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
    $scope.imageOff = ""; // image displayed after mouse leaves.
}

Approach #3: Saving the most interesting method for last! Implementing a directive!!

<div hover-bg-image="{{image}}"></div>

Directive (could be enhanced to revert back to original image if needed... for demonstration purposes only):

.directive('hoverBgImage',function(){
    return {
        link: function(scope, elm, attrs){
            elm.bind('mouseenter',function(){
                this.style.backgroundImage = 'url('+attrs.hoverBgImage+')';
            });
            elm.bind('mouseleave',function(){
                this.style.backgroundImage = '';
            })
        }
    };
});

Controller:

function withDirective($scope){
    $scope.image = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
}

Note: The contents of the controllers could/should ideally be dynamically assigned.

Demonstrations: http://jsfiddle.net/TheSharpieOne/kJgVw/1/

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

Combining the power of Django and AngularJS

Seeking advice on whether my approach is correct or not. I have a website where users can search for items in the database on the home page, and once they find an item, they can click on it to view its details page. While Django allows sending the selected ...

Tips on how to postpone the execution of my ng-init function until my API call is completed successfully

Currently, I am working on a dynamic form that utilizes ng-repeat. To load the location data, I am using oi-select within a modal popup. On click of the modal open button, an API function is triggered to fetch the location values. However, I encountered an ...

Problem with Bootstrap-slider not loading correctly

I seem to be facing an issue with selecting DOM elements that are part of bootstrap-slider. When I try to target them with events like click, nothing happens. All events work fine when the page is refreshed. What could be causing this problem? $(document ...

``Is there a way to activate an on-click event when a user selects a page number from the pagination menu in dat

I am currently implementing datatables and I would like to have an alert box pop up when a user clicks on the pagination numbers in the table. Although I attempted to implement this functionality, it only works for the "next" button as demonstrated below: ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

The step-by-step guide on developing a React Native iOS sharing extension application

Is there a way to enable sharing from apps like WhatsApp, Skype, and Photos in my react-native app? I attempted to use react-native-share-extension, but it only seems to work with Safari. What is the best method for implementing sharing functionality in i ...

The JavaScript if statement does not appear to be accurate

I am encountering issues with my if, else, and else if statements. Here is the code snippet in question: function draw(d) { var testarray = JSON.parse(a); var testarray1 = JSON.parse(a1); var testarray2 = JSON.parse(a2); var Yaxis = $(" ...

Get access to environment variables dynamically using parameters

I'm currently developing a Vue plugin to retrieve the content of environment variables, similar to PHP's env() method. Background: I require a URL in multiple components and have stored it in the .env file anticipating potential future changes. H ...

What is the process of embedding base64 encoded data into an image in Javascript after retrieving the data from Azure Blob Storage?

I am attempting to insert an image by utilizing the base64 data pattern, rather than a URL link. Initially, I retrieve the data from Azure Blob storage using the Azure Node.js SDK: Azure Node.js SDK After downloading the data as a string, I am unsure of ...

I noticed that the single quote (') has been converted to ' How can I correct this issue?

How can I handle the conversion of " ' " to ' in a Dictionary when sent to Django Template? I attempted using the replace function without success. Dictionary_passed = {"-" : "100", "GERMANY" : "1500"} The HTML template output shows: {&#39; ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

Ways to combine multiple then() promises into a single one

I have a section of code where I am using multiple then() methods. I am looking to streamline this and have it only utilize one then(). Is there a way to achieve this? getGreeting = () => { fetch(url) .then((response) => response.json()) ...

Retrieve a string from a universal handler

I am trying to retrieve a string from a generic handler and pass it to angularjs. The code I have written is as follows. Generic handler: public void ProcessRequest(HttpContext context) { List<string> path = new List<string>(); if (con ...

Mastering the art of utilizing Context API and Provider for optimal functionality

Currently, I am working on implementing a dark mode feature in my project. Despite everything appearing to be set up correctly, it seems like the Context at App is not re-rendering when I use the setTheme function inside the Provider. Can someone help me t ...

Prevent the Socket IO event from triggering repeatedly with each call

I've developed an Ionic/AngularJS application that triggers an event in a function to communicate with my Node server. The code snippet below demonstrates how this event is emitted: $scope.doKeywordSearch = function (keyword, details) { var lat ...

Is it possible to retain the volume level setting?

Whenever I am playing music and adjust the volume to 20%, the settings reset to 100% when the bot leaves the voice channel. It's frustrating having to manually set it back to 20% each time. Is there a way for my bot to remember the volume setting? con ...

Having trouble storing JSON data from an $http.get request in AngularJS to a variable or cache?

I'm facing an unusual issue with my AngularJS code. I am trying to retrieve data from a Rest Webservice and though the retrieval is successful, I am unable to save the JSON data to an object. Here is a snippet of my code: services.service('custo ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

Simplify nested JSON data

I'm struggling with a JSON object that looks like this: const people = { name: 'My Name', cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: ...