There are similar questions on this topic but their answers didnt work for my problem.
Im trying to use jQuery's on("click")
to fire a function that simply changes the class of the id which was clicked. But the function is called when the page is loaded and then if you click on what should fire the function it wont.
Here is the html:
<nav>
<ul>
<li id="all" class="tab-current">
<a><span>All Departments</span></a>
</li>
</ul>
</nav>
And here the js:
var $all = $("#all");
$all.on("click", function(){
tabClicked("all");
});
I've also tried this:
$all.on("click", tabClicked("all"));
And this is the function:
function tabClicked(input){
//do some stuff here
}
Any ideas?
var $all = $("#all");
$all.on("click", function(){
tabClicked("all");
});
Try editing it like this. $(function() {});
is like $(document).ready()
, so put function(){}
instead of $(function() {});
.
EDIT:
For some reason, it is firing if script
tag is after elements in html. I tried your code with external JS and etc. - didn't work.
Try like this: JSFiddle
EDIT 2: You should put your handler in $(document).ready()
function anywhere you want, that's the reason.
$( document ).ready(function() {
var $all = $("#all");
$all.on("click", function(){
alert("click");
});
});