jsuissa
jsuissa

Reputation: 1762

jQuery unexpected token error =

I'm getting an "unexpected token =" on the function toggleNav = function(evt){ line of the code sample below. I've went through a number of similar posts, but can't seem to see why it's throwing the error.

Any help pointing me in the right direction is much appreciated.

<script type="text/javascript">
    $(document).ready(function($) {

     $("#nav > li > a").on("click", toggleNav);

    function toggleNav = function(evt){
    var clicked = $(this).parent().attr("class");
    $("#nav").removeClass("btn1 btn2 btn3 btn4 btn5 btn6 btn7").addClass(clicked);
    evt.preventDefault();
}

});
</script>

Upvotes: -1

Views: 120

Answers (4)

mplungjan
mplungjan

Reputation: 177691

This looks more promising

$(function($) {
  $("#nav > li > a").on("click", function(evt) {
    evt.preventDefault();
    var clicked = $(this).parent().attr("class");
    $("#nav").removeClass("btn1 btn2 btn3 btn4 btn5 btn6 btn7").addClass(clicked);
  });
});

Upvotes: 2

Tom Prats
Tom Prats

Reputation: 7911

It is a syntax problem, you're using the function keyword twice there. Choose which way you want to use it. You can do either.

Upvotes: 0

Jerska
Jerska

Reputation: 12002

You should just replace your function toggleNav with var toggleNav, and it should be ok.

Or you could also just remove that anonymous function, and do this way :

function toggleNav (evt) {
    var clicked = $(this).parent().attr("class");
    $("#nav").removeClass("btn1 btn2 btn3 btn4 btn5 btn6 btn7").addClass(clicked);
    evt.preventDefault();
}

Upvotes: 2

GautamD31
GautamD31

Reputation: 28763

Try like this

var toggleNav = function(evt){
    var clicked = $(this).parent().attr("class");
    $("#nav").removeClass("btn1 btn2 btn3 btn4 btn5 btn6 btn7").addClass('clicked');
    evt.preventDefault();
}

or you can directly call like

function toggleNav (evt) {
    var clicked = $(this).parent().attr("class");
    $("#nav").removeClass("btn1 btn2 btn3 btn4 btn5 btn6 btn7").addClass('clicked');
    evt.preventDefault();
}

And also put clicked in quotes because it is an class name

Upvotes: 2

Related Questions