0

I have multiple posts to display in single page. My Java code generates html dynamically, and assign a number to each div.

<div onclick=\"postClicked(" + i + ");\" style=\"cursor: pointer;\">

When I click to a div, I want to go to ReadPost.xhtml page and displayed the details about the clicked post.

function postClicked(id) {  
  localStorage.setItem( 'objectToPass', id );
  location.href = 'ReadPost.xhtml';
}

In the ReadPost page I have the following code:

<h:inputHidden id="postInput" value="#{postManager.clickedPostId};"/> 
 <script>                    
   var myData = localStorage['objectToPass'];
   document.getElementById("postInput").value = myData;
 </script>          

<h:outputText value="#{postManager.displaySinglePost()}" escape="false" />

I want to set the hidden input value with the data in the localStorage. In this way when displaySinglePost() method runs clickedPostId will be already updated and I can display the page with the correct post id. However, postManager.displaySinglePost() runs before the script. How can I make script run before postManager.displaySinglePost() method is called?

tonder
  • 324
  • 3
  • 15
  • This is [Java](https://java.com/en/) and this is [JavaScript](https://www.javascript.com/). They are not the same – theAlexandrian Mar 01 '18 at 02:53
  • I know the difference. Basically, my Java code generating the html code runs before my script. My question is if there is a way to make javascript code run earlier. – tonder Mar 01 '18 at 03:03
  • If your java code generates the html which in turn is the container for javascript, HOW can javascript run before the html or java? – Kukeltje Mar 01 '18 at 07:26

1 Answers1

0

You probably inject the javascript before your button in the dom. To overcome this problem wrap your javascript in an event to make sure your dom is loaded:

document.addEventListener("DOMContentLoaded", function(event) { 
Your javascript goes here
 });
Mick Feller
  • 882
  • 1
  • 8
  • 16