Add CSS styling to a particular div element when a button is clicked

I have been working on a new feature that involves highlighting a div in a specific color and changing the mouse pointer to a hand cursor. I successfully achieved this by adding a CSS class:

.changePointer:hover {
    cursor: pointer;
    background-color: rgb(231, 222, 222);
}

The functionality works as expected when hovering over the div. However, my goal is to trigger this effect only upon clicking a button. I am using Angular 7 for this project. I attempted to utilize

[ngClass]="{'someClass': highlightText}"
, updating the highlightText boolean to true upon button click, but unfortunately, it did not produce the desired outcome. Does anyone have any suggestions?

Answer №1

Utilize the class in the following manner, with active being the class name used.

<div [class.active]="condition"></div>

In your css, include :hover for the active class,

.active:hover {
  background-color: red;
  cursor: pointer;
}

View Demo

Answer №2

Make use of Renderer2 for element's css manipulation.

Sample HTML:

<div class="container">
    <div class="container__item" *ngFor="let div of [1,2,3]" (click)="onClick($event)">
    </div>
</div>

Component Logic:

  import { Component, Renderer2 } from '@angular/core';


  constructor(private rndr2: Renderer2) {}

  onClick(ev) {
    this.rndr2.addClass(ev.target, 'changePointer')
  }

Check out the DEMO: https://stackblitz.com/edit/angular-gaa6zi?file=src/app/app.component.ts

Answer №3

If you're looking to achieve this functionality in JavaScript, utilizing an event listener is the way to go.

button.addEventListener('click', (e) => {
    div.style.backgroundColor = 'rgb(231, 222, 222)';
    div.style.cursor = 'pointer';
});

Answer №4

If you want to change the cursor style, simply add the class .changePointer to the element

function toggleTargets(){
  //Use dataset attribute for selecting targets
  let targets = document.querySelectorAll('[data-type=A]')
  targets.forEach(elem=>elem.classList.toggle('changePointer'))
}
.changePointer:hover {
    cursor: pointer;
    background-color: rgb(231, 222, 222);
}

div{border:1px solid black; margin:5px;}
<button type="button" onclick="toggleTargets()">CLICK</button>

<div data-type=A>A</div>
<div data-type=B>B</div>
<div data-type=C>C</div>
<div data-type=A>D</div>
<div data-type=B>E</div>
<div data-type=C>F</div>
<div data-type=A>G</div>
<div data-type=B>H</div>
<div data-type=C>I</div>

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

Is there a way to switch out the navigation icons on the react-material-ui datepicker?

Can the navigation icons on the react-material-ui datepicker be customized? I've attempted various solutions without any success. <button class="MuiButtonBase-root MuiIconButton-root MuiPickersCalendarHeader-iconButton" tabindex="0&q ...

What is the best way to implement a hover delay for an element in Angular?

Here is an element I'm working with: <div (mouseenter)="enter()" (mouseleave)="leave()">Title</div> In my TypeScript file: onHover = false; enter() { this.onHover = true; // additional functionality... } leav ...

"When setting up a window.EventListener, the Div element fails to be hidden when setting its display property to 'none

I'm working on creating a preloader by displaying an overlay until all the content on the page is loaded. However, despite checking my code multiple times, I can't seem to figure out why it's not working. If anyone could provide some assist ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

Can a button be connected to both navigate to another webpage and trigger a modal to appear on it simultaneously?

Is there a way to connect a button to a modal on a different page so that when the button is clicked, it opens another page (in a new tab with target 0) with the modal already displayed? ...

'Dynamic' styling in Next.js using conditional CSS

I am exploring ways to style elements based on their parameters. I have been searching for terms like "conditional css react" and "implementing conditional styles in react with css". Here is a snippet of my code: e.g. <div class="ChatComponent_ ...

The Nx end-to-end Cypress runner ensures that values from the cypress.env.json file do not overwrite the same entries in the cypress.json environment object

Having encountered an issue with my Nx powered angular project, I am facing a situation where the values provided in a cypress.env.json file are not overriding the corresponding entries in the env object of the cypress.json configuration file. This is a n ...

Modifications made to Angular 7 templates are not appearing in MVC 5

Currently, I am utilizing Angular 7 with MVC5 in Visual Studio 2019. However, I have encountered an issue while trying to render the Angular template in my index.cshtml file. I access the Angular template in index.cshtml using ``. The template loads perfec ...

Generating a PDF file from an HTML and CSS page can be done without relying on APIs or libraries, by leveraging the

Is there a way to directly convert an HTML page generated using PHP and CSS into a PDF format without the use of libraries? I have come across multiple libraries that can accomplish this task, but I would prefer not to rely on any external libraries and i ...

You need to click the form submit image twice in order to make it work

Struggling to get a standard opt-in form to work with an image submit button. The script works fine with a regular submit button, but the image button requires two clicks initially and then one click after unless the page is refreshed. I believe there mig ...

Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized. export class CurrentUser { ...

How can I utilize a variable as the value for ngClass in Angular 2?

Is there a way to use a variable in the ngClass value that gets added to the class list? I have a scenario where I have a set of image sprites, including a base sprite and an active state sprite with "-active" appended to the filename. I insert these sprit ...

Analyzing feedback according to the ResponseHeaders

When sending a request to a REST API using http.get(), the response headers usually contain metadata related to page number, total results, and page count. Angular's HttpClient handles parsing and returning data from the response.body in an Observabl ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

Switching from portrait to landscape view on a mobile website

Currently, I am working on a mobile website where the navigation bar looks great in portrait mode with 15px of padding around the top and bottom. However, when I switch to landscape mode, it occupies almost half of the screen. Does anyone have suggestions ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

Issues with CSS rendering have been observed following an ajax update when using the <ui:repeat> tag

This scenario is a bit intricate. Essentially, I am utilizing Material Design Lite CSS provided by Google and triggering an AJAX request to dynamically add input fields using PrimeFaces. <h:commandLink value="+ Add something> <f:ajax listener ...

Streamlined Boilerplate to Kickstart Your Project

Can anyone suggest a well-crafted boilerplate .less file to kickstart a new project? I'm looking for a comprehensive .less file that includes: CSS Resets styles CSS Normalizer styles CSS3 Helpers (box radius, gradients, box shadow, transition) Basic ...

Personalize your Angular Material experience

Dealing with two components named one.component.html and two.components.html, I encountered an issue when trying to customize the Angular material datepicker for only one component. Writing custom CSS code in one.component.css did not produce the desired ...