How to pass javascript from ". js" to HTML

Asked

Viewed 230 times

-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 would like to have all javascript together in a file ". js"

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

I did the following, 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 doesn’t work. Can anyone help this Noob?

  • you want to put the test.js, inside a js directory?

  • Yes, Gabriel. That won’t be a problem, I’ll do it in production when I understand how to pass the string to HTML. Thank you!

  • If you want to put the test.js file inside a directory it has to look like this in the HTML <script src="js/test.js"></script>

  • And how to pass the javascript result to the user page?

  • I took the test here and is passing normal the generated result

  • https://jsfiddle.net/vitoreis/g34r5cvp/

  • your link does not want to load and in the second part of the JS, the return Document.write(generateId(20));

Show 2 more comments

1 answer

0

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

Try this change using javascript instead of within HTML.

Include an id for your tag <p>:

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

Include function call via javascript.

<script>

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


</script>

Follow the fiddle with example:

https://jsfiddle.net/guidi/kontvLsu/3/

  • But I still have javascript inline instead of ". js", don’t I? Something like this: https://jsfiddle.net/foiovitor/nc4e86vx/

  • No, I put inline only for example, the functions may be within the . external js, then you reference the same file as you had already done and call the function normally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.