0

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>
davidpm4
  • 562
  • 1
  • 7
  • 22

1 Answers1

3

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>
wavemode
  • 2,076
  • 1
  • 19
  • 24
  • [return false](http://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-an-onclick-event) in a javascript event handler prevents the default behavior of the element. For the `a` tag, the default behavior is to navigate to a new page, and `return false` prevents this. – wavemode Apr 23 '14 at 02:49
  • that's strange because I had to add target.preventDefault() to do that. If I just leave in return false; it still navigates to that page AND gives me the popup. – davidpm4 Apr 23 '14 at 02:58
  • 1
    Well as the answer to the linked question points out, the behavior is non-standard, so preventDefault is actually a better option and should work in all modern browsers. – wavemode Apr 23 '14 at 03:03