1

I have a template <script> in my html:

 <script>
         window.daySelected = window.currentdate;
         window.monthSelected = window.currentmonth;
         window.yearSelected = window.currentyear;
 </script>

Here is an example of an external script file loading on a click event: Jquery load script on click event.

Is there a way to load the template script in my html on a click event?

Ernest Soo
  • 194
  • 3
  • 17
  • This is already loaded if it is in your HTML. have you tried inspecting your window.daySelected after your page loads? – Zach M. Jun 07 '17 at 14:29
  • 3
    What are you trying to do? Because if you want to _execute_ this script on the click event, wrap it in a function and call it onclick: ```function setDates(){ window.daySelected = window.currentdate; window.monthSelected = window.currentmonth; window.yearSelected = window.currentyear; }``` and `````` – rickvdbosch Jun 07 '17 at 14:29
  • @ZachM. I am trying to delay the script load. – Ernest Soo Jun 07 '17 at 14:30
  • Okay. Will try it now. @RickvandenBosch – Ernest Soo Jun 07 '17 at 14:30
  • Do what Rick said, wrap it in a function and call it on click. – Zach M. Jun 07 '17 at 14:31

2 Answers2

2

Create a script element and append it into your head tag like the following

function addVals() {
  var sc = document.createElement("script");
  sc.innerHTML = "window.daySelected = window.currentdate; window.monthSelected = window.currentmonth; window.yearSelected = window.currentyear;";
  document.head.appendChild(sc);
}
<input type="button" onclick="addVals()" value="click me" />
jafarbtech
  • 6,842
  • 1
  • 36
  • 55
1

If you want to run a whole javascript file do this

var script = document.createElement("script");
script.src = "url"; // replace url with actual url of script
document.head.appendChild(script);

To add a small script from string form

var script = document.createElement("script");
script.innerHtml = "script"; // replace script with actual script
document.head.appendChild(script);

You could also just create a function

function onClick() {
    // insert your code
}

And you can call it by doing onClick(); using JavaScript

You can also call it from a button by doing <button onclick="onClick()">Click Me</button>

Finally you can also call it from a anchor element by doing <a href="javascript:onClick()">Click Me</a>

nick zoum
  • 7,216
  • 7
  • 36
  • 80