imgkl
imgkl

Reputation: 1082

Button properties revert back to normal after clicking on it

I'm working on a little project and I implemented a button in that with a hover and CSS properties.

But the thing is after clicking on it, it reverts back to the normal basic button. i.e. it loses all it's CSS properties.

I tried to see if the JavaScript is a reason for this change but I failed to find the reason behind it.

HTML

<button class="btn6">1 MB</button>

CSS Button:

.btn6, .btn6:link, .btn6:visited {
  padding: 15px;
  border: 3px solid #333;
  color: #333;
  font-weight: 700;
  text-transform: uppercase;
  font-size: 13px;
  letter-spacing: 3px;
  transition: all .2s ease-in-out;
}
.btn6:hover, .btn6:link:hover, .btn6:visited:hover {
  background: #333;
  border: 3px solid #333;
  color: #fefefe;
  border-radius: 50px;
}

Since the Javascript is long, I provide the link to the codepen ( https://codepen.io/imgkl/pen/XwNyKZ )

The button should retain the CSS properties after clicked.

Upvotes: 4

Views: 1254

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92607

try (inline solution acceptable for little project)

<button class="btn6" onclick="this.classList.add('visited')">1 MB</button>

.btn6, .btn6:link, .btn6:visited {
  padding: 15px;
  border: 3px solid #333;
  color: #333;
  font-weight: 700;
  text-transform: uppercase;
  font-size: 13px;
  letter-spacing: 3px;
  transition: all .2s ease-in-out;
}
.visited, .btn6:hover, .btn6:link:hover, .btn6:visited:hover {
  background: #333;
  border: 3px solid #333;
  color: #fefefe;
  border-radius: 50px;
}
<button class="btn6" onclick="this.classList.add('visited')">1 MB</button>

Upvotes: 1

MauriceNino
MauriceNino

Reputation: 6757

Reason why this happens: You remove all classes from your buttons on click (also btn6)...thats why after the click all look unstyled.

To fix this, change this part of the code:

btns.forEach (btn => {
  btn.className = '';
});

ev.target.className = 'choice';

to this:

btns.forEach (btn => {
  btn.classList.remove('choice');
});

ev.target.classList.add('choice');

For reference - here is the codepen: Link to pen

Upvotes: 5

Related Questions