Mahmood Rehman
Mahmood Rehman

Reputation: 4331

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.

Upvotes: 0

Views: 1964

Answers (2)

Matthew Layton
Matthew Layton

Reputation: 42390

Example using jQuery

 <!DOCTYPE html>
    <html>
        <head>
            <title>Test</title>
            <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $('#myButton').mouseenter(function() {
                        $("head").append($("<script />").prop("type", "text/javascript").prop("src", "http://code.jquery.com/jquery.mobile-1.2.0.js"));
                    });
                });
            </script>
        </head>
        <body>
            <input type="button" id="myButton" value="CLICK" />
        </body>
    </html>

Upvotes: 0

sohel khalifa
sohel khalifa

Reputation: 5588

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.

Upvotes: 2

Related Questions