Can anyone identify the error in that code?

Asked

Viewed 271 times

0

A few days ago I asked a question about how to add class to an elemetho by clicking the button, the answers were satisfactory (I did it using Jquery as suggested), but I decided to create a function using pure javascript only (for study purposes), only there was a bug in the middle of the way and I could not solve, is that someone can find the bug in this code?

sessionStorage.removeItem('Contar');
function AddClass(id){
    //pega o valor do botao
    var tipo = document.getElementById(id).value;
    //pegar o item da lista
    var iten = document.getElementsByTagName('li');
    //cria uma sessão para gravar os valores dos cliques
    if(typeof(Storage)!=="undefined"){
        if(sessionStorage.Contar){
            if(tipo == 'proximo'){
                sessionStorage.Contar=Number(sessionStorage.Contar)+1;
                if(sessionStorage.Contar == iten.length){
                    sessionStorage.Contar=5;
                }
            }else 
            if(tipo == 'anterior'){
                sessionStorage.Contar=Number(sessionStorage.Contar)-1;
                if(sessionStorage.Contar == 0){
                    sessionStorage.Contar=0;
                }
            }
        }else{
            sessionStorage.Contar=0;
        }
    }
    //resgata o valor da sessão
    var valor = sessionStorage.Contar
    if(tipo == 'proximo'){
        if(valor > 0){
            //remove a classe do item anterior
            iten.item(valor-1).removeAttribute('class');
        }
    }else 
    if(tipo == 'anterior'){
        if(valor < 5){
            //remove a classe do item anterior
            iten.item(valor+1).removeAttribute('class');
        }
    }
    //adiciona classe ao próximo item
    iten.item(valor).setAttribute('class', 'selected');
    }

My html is this:

    <button onClick="AddClass('anterior');" id="anterior" value='anterior'>anterior</button>
<button onClick="AddClass('proximo');" id="proximo" value='proximo'>proximo</button>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>

I didn’t post on Jsfidle because on my machine the site is getting all buggy as you can see here:

  • 2

    Give any error on the console?

  • 1

    Yes, when I click on the "previous" button it gives this error: Uncaught Typeerror: Cannot call method 'removeAttribute' of null

  • 2

    So it’s because you’re trying to call this method on an object that hasn’t been initialized. Maybe you have to use brackets instead of parentheses? I think item is an array and not a method, right?

  • 1

    Um dude, I don’t have a very deep knowledge of Javascript, I just started studying a little while ago

  • 2

    No, items are accessed in parentheses. Only if(sessionStorage.Contar == 0) should be sessionStorage.Contar == -1, nay?

2 answers

5

The mistake is in that part:

if(tipo == 'anterior'){
  sessionStorage.Contar=Number(sessionStorage.Contar)-1;
  if(sessionStorage.Contar == 0){
    sessionStorage.Contar=0;
  }
}

the if should be equal to -1 and not 0. the correct would be:

if(tipo == 'anterior'){
  sessionStorage.Contar=Number(sessionStorage.Contar)-1;
  if(sessionStorage.Contar == -1){
    sessionStorage.Contar = 0;
  }
}

What happens is that when Count is subtracted 1, 0-1 = -1 and not 0, as its logic proposed. That’s what I saw, just looking at the code from above.

  • 1

    I got it, I changed it here but it kept going wrong: I think the error is in this part too: if(type == 'previous'){ if(sessionStorage.Count < 5){ //removes the class of the previous item iten.item(value+1). removeAttribute('class'); } } I gave an Alert to test and saw that the value is not adding, on the contrary, it is just concatenating

  • 2

    Before the removeAttribute, puts that line: console.log(iten.item(valor+1)); and see if he’s not putting null on the console

  • 2

    @Felipeavelar Avelar In the end, I was putting as null same, but as it was suggested, I put parseint(sessionStorage.Contar) and it worked XD. Thank you so much for your help!

5


In addition to counter error, it is happening that when you recover the "counter" on the line var valor = sessionStorage.Contar it ends up returning the number as text, so when you try to do valor+1 he does "1" + 1 and that of "11" and on your list there is no item("11") therefore the null.

I used the parseInt to resolve this. Follow the code with the counter changes as well.

function AddClass(id) {
    //pega o valor do botao
    var tipo = document.getElementById(id).value;
    //pegar o item da lista
    var iten = document.getElementsByTagName('li');
    //cria uma sessão para gravar os valores dos cliques
    if(typeof(Storage)!=="undefined"){
        if(sessionStorage.Contar){
            if(tipo == 'proximo'){
                sessionStorage.Contar=Number(sessionStorage.Contar)+1;
                if(sessionStorage.Contar == iten.length){
                    sessionStorage.Contar = iten.length - 1;
                }
            }else 
            if(tipo == 'anterior'){
                sessionStorage.Contar=Number(sessionStorage.Contar)-1;
                if(sessionStorage.Contar < 0){
                    sessionStorage.Contar=0;
                }
            }
        }else{
            sessionStorage.Contar=0;
        }
    }
    //resgata o valor da sessão
    var valor = parseInt(sessionStorage.Contar);
    if(tipo == 'proximo'){
        if(valor > 0){
            //remove a classe do item anterior
            iten.item(valor-1).removeAttribute('class');
        }
    }else 
    if(tipo == 'anterior'){
        if(valor < iten.length){
            //remove a classe do item anterior
            iten.item(valor+1).removeAttribute('class');
        }
    }
    //adiciona classe ao próximo item
    iten.item(valor).setAttribute('class', 'selected');
}

I made a change to count more too, replace the 5 for iten.length - 1

  • 1

    Thanks man! It worked now, I know they are silly mistakes, but I started studying javascript a little while ago XD

  • 1

    Erring that we learn heuaheuea, Javascript has weak typing so you will see these types of problems directly when working with numbers and texts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.