Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Putting the whole script in one function Re: Putting the whole script in one function

#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.

http://codepen.io/pen/134/13

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