FARSOS BULSARA FARSOS BULSARA - 6 months ago 38
Javascript Question

trigger js events like onclick from an external js file

I do sincerely apologize for this question, but this is my 72nd hour of coding in javascript and for reasons unknown to me I can't find the answer to this question.

I need to be able to trigger event handlers like onclick, from an external js file. This is how I have linked my files in my HTML.

<header>
<h1>McMac editing</h1>
<meta charset="utf-8">
<script src="JQuery.js"></script>
<script src="index.js"></script>
</header>


This is how I set up index.js.

var capture = document.getElementById("capture");
capture.onload = function(){console.log="load";};


I will be using cordova eventually, and it says there that inline JS is disabled so this is why I need to get this working and right now with my current setup "load" isn't popping up in my console.

Again, I apologize for the question but I don't know what to do.

Answer

html code :

<html>
<head>
<title></title>
 <style>
     #capture{
         width: 200px;
         height: 200px;
         background-color: aqua;
     }
 </style>  
</head>

<body>
    <div id="capture"></div>
    <script src="index.js"></script>
</body>
</html>

index.js

var ele = document.getElementById("capture");
ele.onclick = function() {
    console.log("click");
}

Note : onload is most often used within the body element :

html code :

<html>
<head>
<title></title>
 <style>
 </style>  
</head>
<body id="capture" >
    <script src="index.js"></script>
</body>
</html>

index.js :

var ele = document.getElementById("capture");
ele.onload = function() {
    console.log("load");
}
Comments