0

Well I have the following inline JavaScript events in my .HTML file and I want to put their JavaScript alternatives in a .JS file. Then I'll link the .JS file to the .HTML file. Here are the events:

oncontextmenu
onmousedown
onload
onclick
onerror
onmouseover
onmouseout
3
  • Are you including a library like jQuery? Commented Mar 15, 2014 at 23:06
  • @JonKoops - there's a jQuery tag on the question. Commented Mar 15, 2014 at 23:14
  • Yeah I do it's jQuery 1.4.3.min.js. But I'd like to use just plain JavaScript since I'm not very familiar with jQuery. Commented Mar 16, 2014 at 10:07

2 Answers 2

2
<div id = "yourElement"></div>
<script>
    var yourElement = document.getElementById("yourElement"); //get the element
    yourElement.oncontextmenu = function () {
        //oncontextmenu triggered!
    }
    yourElement.onmousedown = function () {
        //onmousedown triggered!
    }
    yourElement.onload = function () {
        //onload triggered!
    }
    //ecc..
</script>


EDIT:

here's my fiddle: http://jsfiddle.net/durZL/

Note: if you put the script in the header you should tell to the javascript to run the code when the page is fully loaded, or else you are not able to get the element,
jQuery already does this for you, but if don't want to use it this is the right way to do it:

window.onload = function () {
   //here is the code that will run after the page is fully loaded
   //DOM elements can be safely manipulated here
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're going to have to attach event handlers from your external JS file.

If your using jQuery (would recommend for this kind of selector heavy stuff):

$('some selector').on('some event', function( evt ) { /* Do some stuff here */ });

Or if you don't want to use jQuery:

document.querySelector('some selector').addEventListener('some event', function( evt ) { /* Do some stuff here */ });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.