3

I have a blade code like this:

<input type='text' id="input1">
<div >
 <h3 id="showData"> Data will be shown here  </h3>

</div>

<script>
  var input=document.getElementById('input1').value;

  document.getElementById('showData').innerHTML=input;
</script>

What I want is to write the script part in a separate file (say called externalScript.js) and call it here in the blade file.

Also, I have a doubt about it. If I do that, since the script is run from an external file, how will it fetch the id values like input1 or showData ?

2 Answers 2

3

Write a new file called: externalScript1.js

Add the script tag, best in the head or foot part of your code.

    <script src="{{ asset('externalScript1.js') }}" defer></script>

(the asset helper gets the path to the public folder, https://laravel.com/docs/8.x/helpers#method-asset)

In the end everything will load from one page, ergo the elements are found, so you won't have a problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I had to use the same script everywhere, now, all I need to do is use the source
2

Just add js file in laravel resources directory, link to webpack and compile more info.

when it comes to executing the script, attach it at the end of the page (before </body>) or wait for the page to be loaded document.addEventListener('DOMContentLoaded', function() {})

Attach the js file in the main wrapper, not in the nested blade element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.