Search code examples
javascriptdom-events

Load js file on mouseover JavaScript


Is it possible to load js file on some event like mouseover or click? I try to load a whole js file not a specific function.


Solution

  • This example loads the specified js file on onClick() event of button

    <button onclick="myFunction()">Click me</button>
    
    <script type="text/javascript">
       function myFunction(){
    
              var file = document.createElement("script");
              file.setAttribute("type", "text/javascript");
              file.setAttribute("src", "js/js_file.js");
              document.getElementsByTagName("head")[0].appendChild(file);
    
       }
    </script>
    

    Similarly, you can also load the js on onMouseOver() event of the button or any other HTML element.