How to pass javascript from ".js" to HTML

-1

I have the following code embedded in my HTML:

<script>
// dec2hex :: Integer -> String
function dec2hex (dec) {
  return ('0' + dec.toString(16)).substr(-2)
}

// generateId :: Integer -> String
function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, dec2hex).join('')
}   
document.write(generateId(20))
</script>

Everything works fine but I would like to have all the javascript together in a ".js" file

My question is how to move to a ".js" file and return the result to HTML?

I did the following, I created a "test.js" with:

// dec2hex :: Integer -> String
function dec2hex (dec) {
  return ('0' + dec.toString(16)).substr(-2)
}

// generateId :: Integer -> String
function generateId (len) {
  var arr = new Uint8Array((len || 40) / 2)
  window.crypto.getRandomValues(arr)
  return Array.from(arr, dec2hex).join('')
}   

And in HTML:

<!DOCTYPE html>
<html>
<head>
  <script src="js/teste.js"></script>
  <meta charset="utf-8">
  <title>Random String Generator</title>
</head>
<body>
    <p>generateId: id="generateId(20)"</p>
</body>
</html>

It does not work. Can anyone help this noob?

    
asked by anonymous 18.08.2018 / 21:13

1 answer

0

I believe you have to tweak your html, the way you did the result is just text and you are not calling the function.

Try to make this change through the javascript itself rather than within HTML.

Include an id for your tag <p> :

<p id="paragrafo"> </p>

Include the function call via javascript.

<script>

    window.onload = function(){
     document.getElementById('paragrafo').innerHTML = "GeneratedId: id=" 
     +generateId(20);
}


</script>

Follow the example fiddle:

link

    
18.08.2018 / 22:14