Javascript to change class in <ul> tag not working

151 views Asked by At

Based on the size of the window, I'm trying to alter the class of a tag:

<ul id="navul" class="nav navbar-nav">

and making it instead be:

<ul id="navul" class="nav nav-pills">

This is what I am trying, and isn't working:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $(window).resize(function () {
            $("count").text(x += 1);

            if ($window.width() < 768) {
                $('#navul')
                    .removeClass('navbar-nav')
                    .addClass('nav-pills');
            };
            if ($window.width() > 769) {
                $('#navul')
                    .removeClass('navbar-pills')
                    .addClass('nav-bar');
            };

        });
    });
</script>

I've also tried wrapping it inside

$(document).ready(function () {
    ....
});

From watching DOM in dev tools, it would seem as if the script is not firing at all. I'm probably missing something simple.

EDIT:

I used this as my starting template:

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_resize

This script works perfectly without $(window) being declared.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
x = 0;
$(document).ready(function(){
    $(window).resize(function(){
        $("span").text(x += 1);
    });
});
</script>

<p>Window resized <span>0</span> times.</p>
3

There are 3 answers

5
Nakib On BEST ANSWER

There is nothing like $window and it will give you error and wont run the script change $window.width() to

$(window).width()

$window will give you error of undefined

1
Geoffroy On

Maybe because your $window variable is undefined?
Try this:

<script type="text/javascript">
    var $window = $(window);
    $window.resize(function () {
        if ($window.width() < 768) {
            if ($('#navul').hasClass('navbar-nav')) {
                $('#navul').removeClass('navbar-nav').addClass('nav-pills');
            }
        };
        if ($window.width() > 769) {
            if ($('#navul').hasClass('nav-pills')) {
                $('#navul').removeClass('nav-pills').addClass('navbar-nav');
            }
        };
    });
</script>
2
adelindev On
$(window).resize(function () {
  $('#navul')
    .removeClass('navbar-nav nav-pills')
    .addClass(($(window).width() < 768 ) ? 'nav-pills' : 'navbar-nav');
});