I am facing an issue with reusing a javascript function in two JSP pages. Both pages have anchors that trigger a database operation when clicked. To avoid duplicating the script, I am considering creating a separate JSP page specifically for this script and including it in both pages. Is this a good approach to reusing javascript? Are there any better alternatives?
Here is a snippet of the script:
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
UPDATE
I have moved the script to a common.js file located at scripts/common.js.
I used the <spring:url>
tag to render the URL to this script.
<spring:url value="/resources/scripts/common.js" var="common_js" />
<script src="${common_js}" type="text/javascript"><jsp:text/></script>
I configured Spring to load this script by specifying these resources in a context file:
<resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
However, the script is not getting loaded in the JSP Pages. Any suggestions on troubleshooting this issue?
UPDATE
I found a solution by wrapping the script inside a function():
(function(){
alert("test");
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
})(jQuery);