user3052659 user3052659 - 6 months ago 26
Javascript Question

Inline jQuery unexpected token switch

Stumped as to why this simple code keeps giving me a


Uncaught SyntaxError: Unexpected token switch


<script>
$(document).ready(function() {
setInterval('switch()', 5000);
});

function switch(){
var $active = $('#placeholder img.active');
var $next = $active.next();

$next.addClass('active');
$active.removeClass('active');
}
</script>


I thought functions can be outside the
document.ready
function? When I tried putting
switch()
inside the
.ready
function, it gave me the same error. My jsfiddle: https://jsfiddle.net/kL1Lrb2z/1/

Answer

As the error message indicates, switch is a keyword, and thus may not be used as a function name. To fix the issue, rename your function to something else, such as mySwitch.

Comments