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?

5
  • This is already loaded if it is in your HTML. have you tried inspecting your window.daySelected after your page loads? Commented Jun 7, 2017 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 <img src='blah' onclick='setDates()' /> Commented Jun 7, 2017 at 14:29
  • @ZachM. I am trying to delay the script load. Commented Jun 7, 2017 at 14:30
  • Okay. Will try it now. @RickvandenBosch Commented Jun 7, 2017 at 14:30
  • Do what Rick said, wrap it in a function and call it on click. Commented Jun 7, 2017 at 14:31

2 Answers 2

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" />

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

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.