Home › Forums › JavaScript › Putting the whole script in one function › Re: Putting the whole script in one function
April 29, 2012 at 11:20 pm
#101984
seanroberts
Member
First of all, you need to put your li in an ul or ol.
Second, if you are using jQuery, according to your source you are, this process can be expedited.
html:
Script: (assuming jQuery is being called before this)
(function() {
//handle click event for the li
$("#list li").on("click", function(e){
if(!$(this).hasClass("active")) {
//if an element by default is not given the
//"active" class you need to check to see
//if the object is undefined
if($("#list .active") != "undefined"){
//remove the class from the current element
$("#list .active").removeClass("active");
}
//add the class to the elment being clicked
$(this).addClass("active");
}else {
//the element is alread "active"
return false;
}
});
}());
Hope that helps