I have such a function, it is launched through the submit button in the form with id="savebaseform" :

 $('savebaseform').addEventListener('submit', function(event) { event.preventDefault(); var BB = get_blob(); saveAs( new BB( [savebasetext] , {type: 'text/plain;charset=utf-8' + document.characterSet} ) , (databases[nowbase][0].name) + '.txt' ); }, false); 

How can I make this function run via a regular link, for example <a href="#" id="save">click</a> ?

  • $('savebaseform').addEventListener('submit' replace with $('#savebaseform').on('submit' - Stack

1 answer 1

Well, firstly, your code should not work, because 1) the form should not be selected as $ ('savebaseform') but as $ ('# savebaseform') 2) addEventListener is a DOM object method, but what you Wrote - this is a jquery wrapper over a DOM object. In your case, document.getElementById ('savebaseform') is appropriate. AddEventListener ()

Well, in essence, you can wrap the body of the event handler in a separate function and call it by clicking on the link. Like this:

 function foo(e) { var BB = get_blob(); saveAs( new BB( [savebasetext] , {type: 'text/plain;charset=utf-8' + document.characterSet} ) , (databases[nowbase][0].name) + '.txt' ); } document.getElementById('save').addEventListener('click', foo); 

And the link code is:

 <a href="javascript:void(0);" id="save">click</a> 
  • and for what void(0) ? - Stack
  • 2
    @Stack is instead of # , so that by clicking on the link it (the grid) is not added to the URL and the page is not scrolled to the top. This entry overrides the default action. - Ivan Frolov