0

I am working on an assignment that uses jquery's load() function to build a single page application

index.jsp

<body>
  <div id="center-pane">
    <!-- JQUERY LOADS COMPONENTS HERE -->
  </div>
  <script src="${pageContext.request.contextPath}/resources/js/script.js"></script>
</body>

This gets called at some point in script.js

$("#center-pane").load("otherPage.jsp")

This line exists in otherPage.jsp

<a class="testPrinting">Testing</a>

I want the contents of otherPage.jsp to be loaded into the div on index.jsp, which it does, and then have the following function execute as such in script.js

$(".testPrinting").on('click',function(){
    console.log("Success!");
};

It seems to not work because otherPage.jsp is loaded after the javascript has already been loaded, at which point the element with class "testPrinting" doesn't exist.

However, if I change the line in otherPage.jsp to this:

<a onclick="logToConsole()">Testing</a>

the console log works.

Is there any way to get this functionality to work using the jquery selector instead of the onclick?

  • 1
    Note the mention of delegate event handlers in the accepted answer – Taplar Dec 05 '17 at 22:54
  • why do you want to load jsp with javascript? – tiborK Dec 05 '17 at 22:58
  • I'm loading the jsp with javascript because on index.jsp I have toolbars that I don't want to be reloaded. So I just want to update the center component. Correct me if my thinking is wrong on this please. – user123456789 Dec 05 '17 at 23:29

0 Answers0