Javascript, HTML and onClick - function not defined

I am trying to make the "Insert Link" button in the Rich Text Editor in Javascript. Basically, what he will do is add the following code to his code:

<a href="linkGoesHere" onClick="someJSFunction();"> textGoesHere </a> 

The trick someJSFunction() should fire when the user clicks a button inside the editor itself. I wrote a Javascript function that adds this code when the "Insert Link" button is clicked, for example:

 editor.setContent(previousContent + theHtmlCode); 

However, when I click the someJSFunction() link, it does not start, and instead I get a "Function not defined" error. I tried to define someJSFunction() in the global scope, but it still won't see it. It’s strange even if I do something ugly, like adding

 <script type="text/javascript"> *(I define someJSFunction() here)* </script> <a href="linkGoesHere" onClick="someJSFunction();"> textGoesHere </a> 

for the contents of the editor, it will still produce the same error. I saw several people in SO with the same problem, but they somehow managed to solve this problem by defining their functions in a global area.

Please note that I cannot edit the HTML directly, so I have to resort to using a piece of Javscript that inserts a piece of HTML, which in turn will invoke another piece of Javascript.

And before you ask, no, I will not use jQuery.

+5
source share
2 answers
  1. Avoid declaring events in HTML
  2. Avoid persistent

The code below should work.

HTML

 <textarea id="editor"></textarea> <a id="link" href="#">Link</a> 

Javascript

 var link = document.getElementById('link'); link.addEventListener('click', editContent); function editContent() { var editor = document.getElementById('editor'); editor.value += "text"; } 

Jsfiddle for example above https://jsfiddle.net/ar54w16L/

Enjoy it!

0
source

Try onclick instead of onClick in HTML.

0
source

Source: https://habr.com/ru/post/958806/


All Articles