How can JavaScript be effectively reused across two JSP pages for improved efficiency?

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);

Answer №1

To implement an external JavaScript file, you can create a separate .js file and then reference it from both JSP pages. Here's an example:

<script src="displaydate.js" type="text/javascript"></script>

For more information on using external JavaScript files, you can visit this link:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Django model form not triggering Jquery Ajax submit()

Despite numerous attempts and code modifications, I cannot get the submit() function to work correctly. Strangely, when using a click event instead, the callback is triggered and the ajax() function runs smoothly. Even after scouring multiple tutorials and ...

transferring numerous parameters in a servlet using AJAX

function retrieveXmlHttpRequest() { var xmlHttp = false; if (window.XMLHttpRequest) { return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safar ...

Unable to render JSON object on JSP page

I am currently working on a JSP page where I am attempting to retrieve a JSON object from my servlet. Here is the JSP code snippet: <%@page import="org.codehaus.jettison.json.JSONObject"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transition ...

What is the Vue.js equivalent of Angular's ng-container?

When working with Angular, you may come across a tag called ng-container which is used in the following way: <ng-container *ngIf="false">this won't be shown</ng-container> According to the Angular documentation: The Angular is a grou ...

Error message "Session ID invalid when running multiple tests" indicates that there

After receiving no response to my previous inquiry, I am reposting the question with the current code structure: The parent class has a @BeforeEach method that initializes everything: public class WebDriverSettings { public static WebDriver driver; ...

Encountering an issue with TS / yarn where an exported const object cannot be utilized in a consuming

I am currently working on a private project using TypeScript and Yarn. In this project, I have developed a package that is meant to be utilized by one or more other applications. However, as I started to work on the consumer application, I encountered an ...

What is the relationship between JavaScript node modules and vanilla script references within the browser environment?

When using the modular javascript approach with Node.JS + npm and browserify, how do you handle situations where you need to use javascript libraries that are not available on npm? Some of these libraries may not be compatible with modularity (amd/commonJs ...

Exception: The specified driver at /resources/phantomjs-2.1.1-linux-x86_64/bin/phantomjs is not executable

Currently, I am attempting to execute a selenium UI test in headless mode within Jenkins on Unix. I have made sure to use the appropriate version of phantomJS that is compatible with Unix environments. phantomjs-2.1.1-linux-x86_64/bin/phantomjs However, ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...

How can I toggle the radio button based on the dropdown selection?

I'm attempting to enable or disable a radio button based on the selection from a dropdown menu. View my jsfiddle example here For example, if the user selects "persons" from the dropdown, only the options for Anthony and Paul should be available to ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Calculate the total sum by adding the values of the radio buttons that have been selected and then display or

Seeking help to troubleshoot my code! I want to calculate the sum of selected radio button values and display it at the end. Can anyone assist me with this issue? Thanks in advance! <html> <head> </head> <script type="text/javas ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

The functionality of routerLink is not functioning as expected when used on button elements

My dashboard is designed to display information retrieved from Firebase. However, I am facing an issue with a button labeled as (more) that should redirect me to a specific page when clicked. Unfortunately, the button doesn't seem to be working as int ...

Using the HTML form element to achieve two-way binding on array elements

I am working with an array of objects within a component that will be iterated in the template. app.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.compone ...

Calculating the number of characters in a Java character array

Just starting out with Java and trying to create a program that prompts the user for strings, prints those strings as they are entered, converts them to lowercase, removes spaces, and then creates a character array of the alphabet with asterisks showing th ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...