JavaScript AppendChild display for a short moment before being reset

I am trying to insert some HTML data into a div tag using a hyperlink that calls a Javascript function upon clicking on the hyperlink.

The HTML data works and the items I am it to show up appears but it disappears immediately after executing.

I have tried event.preventDefault() which works on Chrome based browsers but does not work on Firefox. I have tried 'return false' at the end of the Javascript function but it doesn't work.

The code is below:

<div id="doHere"></div>
<p>Toggle <a href="" onclick="toggle()">HERE</a> !!!</p>
<script>
  function toggle() {
    // event.preventDefault(); // Does not work on Firefox
    document.getElementById('doHere').innerHTML = '<ol><li> Test test </li></ol>';
    // return false; // Not working on both Chrome and Firefox
  }
</script>

How do I ensure that the edited HTML is permanent ?

3 answers

  • answered 2018-07-11 05:17 Mamun

    In Firefox there is no global event property and you will get the following error:

    ReferenceError: event is not defined

    To fix the issue you have to pass event property to the function so that you can refer that at a later time:

    <html>
        <body>      
            <div id="doHere"></div>        
            <p>Toggle <a href="" onclick="toggle(event)">HERE</a> !!!</p>        
            <script>
                function toggle(e) {
                    e.preventDefault();
                    document.getElementById('doHere').innerHTML = '<ol><li> Test test </li></ol>';
                }
            </script>
        </body>
    </html>

  • answered 2018-07-11 05:22 Dananjaya Ariyasena

    Try with "#" value for href

    <div id="doHere"></div>
    <p>Toggle <a href="#" onclick="toggle()">HERE</a> !!!</p>
    <script>
      function toggle() {
        // event.preventDefault(); // Does not work on Firefox
        document.getElementById('doHere').innerHTML = '<ol><li> Test test </li></ol>';
        // return false; // Not working on both Chrome and Firefox
      }
    </script>

  • answered 2018-07-11 05:27 Komal

    Use javascript:void(0); in href attribute:

    <html>
        <body>      
            <div id="doHere"></div>        
            <p>Toggle <a href="javascript:void(0);" onclick="toggle()">HERE</a> !!!</p>        
            <script>
                function toggle() {
                    document.getElementById('doHere').innerHTML = '<ol><li> Test test </li></ol>';
                }
            </script>
        </body>
    </html>