Problem with a JavaScript function

2

I have a problem here and I do not know how to solve, in theory, my function below 768px was to add the class .navbar-inverse to the tag nav , and above 768px is to remove it case exists, but nothing happens.

Edit: I've done some tests and I've seen that he is ALWAYS removing this class and therefore giving trouble.

My JS looks like this:

 $(document).ready(function () {
    $(window).resize(function () {
  var $element = $("nav");
    /*Abaixo de 768px, add a classe .navbar-inverse*/
  if (window.innerWidth < 768) {
      if(!$element.hasClass(".navbar-inverse")) {
          $element.addClass(".navbar-inverse")
        }
  }
    /* Acima de 768px, se existir a classe navbar-inverse ela é retirada*/

  if (window.innerWidth > 768) {
      if($element.hasClass(".navbar-inverse")) {
          $element.removeClass(".navbar-inverse")
      }
  } 
});
});

I can not see the problem, the nav tag exists, but nothing happens.

    
asked by anonymous 14.04.2015 / 15:47

2 answers

7

The problem is that hasClass , addClass , and removeClass expect the class name, not a selector. So it is not to put the point in the beginning. Otherwise,% s of% s that verify that the element already has the class are unnecessary, and can optimize performance by avoiding looking for the element at all times. I would do so:

$(document).ready(function () {
    var $element = $("nav");
    $(window).resize(function () {    
        /*Abaixo de 768px, add a classe .navbar-inverse*/
        if (window.innerWidth < 768) {
            $element.addClass("navbar-inverse");
        /* Acima de 768px, se existir a classe navbar-inverse ela é retirada*/
        } else {
            $element.removeClass("navbar-inverse");
        }
    });
});
    
14.04.2015 / 15:57
4

Removes the . from the jQuery selector in the functions hasClass , addClass and removeClass .

Try:

$(document).ready(function () {

    $(window).resize(function () {

        var $element = $("nav");

        /*Abaixo de 768px, add a classe .navbar-inverse*/
        if (window.innerWidth < 768) {
            if (!$element.hasClass("navbar-inverse")) {
                $element.addClass("navbar-inverse")
            }
        }

        /* Acima de 768px, se existir a classe navbar-inverse ela é retirada*/
        if (window.innerWidth > 768) {
            if ($element.hasClass("navbar-inverse")) {
                $element.removeClass("navbar-inverse")
            }
        }
    });
});
    
14.04.2015 / 15:58