-1

I have a function where you can click to like, and you kan also click to dislike. How can I make it NOT possible to go to negative number, so that if you click dislike after 0 it stays 0?

function stem(id) {
    var antal_stemmer = document.getElementById(id).className; 
    var nyt_antal_stemmer =+ antal_stemmer + +1; 
    document.getElementById(id).className = nyt_antal_stemmer;
    var indhold = document.getElementsByClassName(id); 
    var indholdA = indhold[0].innerHTML; 
    indhold[0].innerHTML = nyt_antal_stemmer + " stemmer"; 
}
function fjern(id) {
    var antal_stemmer = document.getElementById(id).className;
    var nyt_antal_stemmer =+ antal_stemmer - +1;
    document.getElementById(id).className = nyt_antal_stemmer;
    var indhold = document.getElementsByClassName(id);
    var indholdA = indhold[0].innerHTML;
    indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}

  • 1
    whare is the part where you decrement a value? – Nina Scholz Jan 06 '20 at 21:22
  • 1
    @NinaScholz perhaps `var nyt_antal_stemmer =+ antal_stemmer - +1;` but...it looks weird. – VLAZ Jan 06 '20 at 21:24
  • 1
    Why do you write `- +1` instead of just `- 1`? – Barmar Jan 06 '20 at 21:25
  • And why do you write `=+`? At first I mistook that for `+=` and thought you were incrementing `nyt_antal_stemmer`. – Barmar Jan 06 '20 at 21:26
  • 1
    `nyt_antal_stemmer =+ antal_stemmer - +1;` is a really, really confusing way to write `nyt_antal_stemmer = antal_stemmer - 1;` – Klaycon Jan 06 '20 at 21:26
  • @Barmar my guess is that `=+` is because `antal_stemmer` is a string, so it's actually more properly written as `var nyt_antal_stemmer = (+antal_stemmer) - 1`. However, speaking of `antal_stemmer`, it's the value of a *class*. It should probably be a `data-*` attribute instead. – VLAZ Jan 06 '20 at 21:28

1 Answers1

1

You could get the maximum of the value or zero. The result is a number greater or equal zero.

var nyt_antal_stemmer = Math.max(0, antal_stemmer - 1); // - converts the operands to number
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392