0

So I am looking for a way to introduce some new CSS whenever an element has been clicked, and then have that stay afterwards. It's really the last part that I can't get to work.

Here's my code so far:

HTML

<body>
    <p>Click me</p>
</body>

CSS

#elmt:active{
   background-color: lightgreen;
}

So I want the background color to stay light green from whenever you click the #elmt the first time, and not go back to the default color when you release the mouse.

Is this even possible?

Tobias H.
  • 426
  • 1
  • 6
  • 18

3 Answers3

2

you can't do that with css only

//get your element 
document.getElementById("#elmt").addEventListener("click", (e)>{
// get the other element 
document.getElementById("#theOtherName").style.backgroundColor = "lightgreen";
})
scr2em
  • 974
  • 8
  • 17
2

You could toggle a css class on click pretty easily with a bit of javascript:

document.body.addEventListener('click', 
  (e) => e.target.classList.toggle('active')
);
.active {
  background: lightgreen;
}
<p>Click me</p>
<p>Or me</p>

As Stephen P points out in a comment below you'll want to be more selective about which elements you target--in the snippet above you can toggle the background on body if you click between the paragraphs, for example--but this was just a quick proof of concept.

ray
  • 26,557
  • 5
  • 28
  • 27
  • This is absolutely the strategy I'd use but, Tobias, be aware that once you start nesting elements things get a little more complicated. Try it with a list `
    • 1
    • 2
    • 3
    ` you'll find you can toggle the individual `li` elements but you can also toggle the `ul` itself.
    – Stephen P Oct 15 '21 at 18:09
0

If your element is not a focusable element, you need to add the tabindex attribute, so it can catch the click event , and be clicked,focused and active.

Once the clicking part is solved, you can add a transition-delay of a lifetime on the regular state, so it seems like style remains.

exemple (duplicate of : Make CSS Hover state remain after "unhovering" ):

p[tabindex] {
  transition-duration: 0;
  transition-delay: 99999s;
}

p[tabindex]:active {
  transition-delay: 0s;
  background-color: lightgreen;
}
<p tabindex="0">Click me</p>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129