Title

Thursday, 5 February 2015

move old inline JavaScript


I have this small component that opens a window onclick. The problem is its inline JavaScript, and I know that is dated and ugly. How can I move it down below and keep the same functionality? This isn't my code, I'm just trying to learn :) I've tried to target the a tag via its ID, and then add an event listener but then I get errors saying focus is undefined and the link just uses its default functionality and take me to the url in the same window. Any pointer? I'd really appreciate the help!

<body>   <a id="tower" href="http://static.slh.com/files//HUPARSR/Large_Gallery_02_HUPARSR_53800328_Exterior_-_Eiffel_tower_view_400x600_72.jpeg"   onClick='showPDF(this.href);return(false);'>   Click here to see the Eiffel Tower.   </a>  <script>  function showPDF(url) {  newwindow=window.open(url,'name','height=400,width=600,top=100,left=100,resizable');  if (window.focus) {newwindow.focus()}  }  </script>  </body>
Answer

Remove onclick from the a element and attach an event listener with javascript:

<script>  document.getElementById("tower").addEventListener("click", function() {   showPDF(this.href);   return false;  });  // ... your other code below ...  </script>

No comments:

Post a Comment