css is not a Function

Asked

Viewed 353 times

2

I have an array of items that I want to change the css in the scroll of my Document, when I give a console.log(), the items are there, but in the loop to change their style, give me the message:

Uncaught Typeerror: itensmenu[i]. css is not a Function

Call of the event Scroll:

 $(document).scroll(function(){
       var brand  = $('#brand');
       var posicao = window.pageYOffset;
       var navbar = $('#navbar');
       var itensmenu = $(".nav-item");
       var topo = $("#topo");
       trocaNav(navbar, topo, posicao, brand, itensmenu);

    });

Loop:

function trocaNav(navbar, topo, posicao, brand, itensmenu){
  if (posicao == 0){
    navbar.css("background-color", "transparent");
    brand.attr("src","img/logo_BP.png");
  } else{
    navbar.css("background-color", "white");
    brand.attr("src","img/logo.png");
  }

  for(var i = 0; i < itensmenu.length; i++){
    if (posicao == 0) {
      itensmenu[i].css("background-color", "white");
      itensmenu[i].css("color" , "white" );
    } else{
      itensmenu[i].css("background-color", "black");
      itensmenu[i].css("color", "black");         
    }
  }

}

1 answer

5


The use of [index] in jQuery DOM only works to catch the first item as it is a "shortcut", to catch other items you must use or .each or .eq

Do so:

.eq returns the jQuery object and .get returns the DOM element

  for(var i = 0; i < itensmenu.length; i++){
    var current = itensmenu.eq(i);

    if (posicao == 0) {
      current.css("background-color", "white");
      current.css("color" , "white" );
    } else{
      current.css("background-color", "black");
      current.css("color", "black");         
    }
  }

Or rather it would be so:

var bg = "white", cor = "white";

if (posicao == 0) {
    bg = "black";
    cor = "black";
}

for(var i = 0; i < itensmenu.length; i++){
  var current = itensmenu.eq(i);

  current.css("background-color", bg);
  current.css("color", cor);
}

Or so, with .each:

var bg = "white", cor = "white";

if (posicao == 0) {
    bg = "black";
    cor = "black";
}

itensmenu.each(function (i) {
  $(this).css({
      "background-color": bg,
      "color": cor
  });
});
  • I made some adaptations, the third way worked perfectly.

  • 2

    @Guilhermenascimento the return is different, but in this case it would also work with certainty http://stackoverflow.com/questions/4709660/jquery-eq-vs-get I already delete the comment

  • @Guilhermenascimento ok, but you can always put that addition, it would have more visibility

  • @Guilhermebirth of nothing, rich response

Browser other questions tagged

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