Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox link to javascript function opens a new window when not intended

I have this problem where when I have this html in firefox it opens a new window

<a style="float:right;" 
href='javascript:window.location.href="#";'onClick="javascript:addNewRecord();">
New Record</a>

I have tried self.location, window.location, #body, and #h1 as the href.

Originally I had the code as, but in firefox that did not do anything but open a fresh window, and not perform my function. The code works perfect in chrome.

<a style="float:right;" href="javascript:addNewRecord();">New Record</a>
like image 889
richsoni Avatar asked Dec 03 '22 11:12

richsoni


2 Answers

The canonical inline way is

<a style="float:right;" href="#"
onClick="addNewRecord(); return false">New Record</a>

or better:

<a style="float:right;" href="#"
onClick="return addNewRecord()">New Record</a>

where addNewRecord returns false at the end of the function


An even better way is

window.onload=function() {
  document.getElementById("addLink").onclick=addNewRecord;
}
function addNewRecord() {
  ...
  return false;
}

plus

<style>
#addLink { float:right }
</style>

and

<a href="#" id="addLink">New Record</a>

Since abusing the HREF on a link going nowhere just to get a pointer is frowned upon, you may consider a <span> with an onclick and a cursor:pointer. It does need more effort to make such an element accessible to for example screen readers.

like image 120
mplungjan Avatar answered Mar 15 '23 00:03

mplungjan


try :

onClick="addNewRecord();return false"
like image 41
thiswayup Avatar answered Mar 14 '23 23:03

thiswayup