0

In the DIV there is js like: onclick, onkey down etc.. How do I set this up on a new javascript file without losing the functionality. I already have a external js file. And I want to add the 'onclick' stuff in there. But I'm not sure how to do it, and to make it work.

Can someone help me?

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>

  <link rel="stylesheet" type="text/css" href="raad.css">

</head>

<body>
  <h1>This is a Heading</h1>
  <p>This is a paragraph.</p>

  <div id="container">

<h1>Raad het goede nummer!</h1>

    <div id="message_txt"></div>
    <form id="userInput" name="userInput" method="post">
        <input id="input_txt" name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,3);" onKeyUp="limitText(this.form.limitedtextfield,3);" maxlength="3">
        <br />
        <button id="guess_btn" type="button" onclick="guessNumber()">RAAD</button>
        <br />
        <button id="playAgain_btn" type="button" onclick="initGame()">OPNIEUW</button>
    </form>
</div>

<script type="text/javascript" src="raad.js"></script>

</body>

</html>

3

4 Answers 4

1

You can move all event handler attributes away from HTML into JS using addEventListener.


So, for example, this:

<input id="input_txt" name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,3);" onKeyUp="limitText(this.form.limitedtextfield,3);" maxlength="3">

should become this:

HTML

<input id="input_txt" name="limitedtextfield" type="text" maxlength="3">

JS

var input_txt = document.getElementById('input_txt');

input_txt.addEventListener('keydown', function(e){
    limitText(this.form.limitedtextfield,3);
});
input_txt.addEventListener('keyup', function(e){
    limitText(this.form.limitedtextfield,3);
});

Ideally, you could use a common function for the callback, like this:

function handleInputKeys() {
    limitText(this.form.limitedtextfield,3);
}

And then simply have:

input_txt.addEventListener('keyup', handleInputKeys);

Next example, this:

<button id="guess_btn" type="button" onclick="guessNumber()">RAAD</button>

Should be:

HTML

<button id="guess_btn" type="button">RAAD</button>

JS

var guess_btn = document.getElementById('guess_btn');

guess_btn.addEventListener('click', guessNumber);

etc...

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

5 Comments

Thank you this really helped me out! Just beginning with coding and still a student :)
just as additional info on addEventListener and onclick: stackoverflow.com/questions/6348494/addeventlistener-vs-onclick
You're welcome, I'm glad I could help! :) You were on a right track with the idea of keeping your code neat by separating JS from HTML, and now you know a few good practices on how to implement it.
<input id="input_txt" name="limitedtextfield" type="text" maxlength="3"> is this also HTML or is it the maxlength css?
It has to be HTML because CSS doesn't have such functionality (yet).
1

You can do something like this on your javascript file:

document.getElementById("guess_btn").onclick = function() {guessNumber()};

function guessNumber() {
    ......
}

And then do the same for the other events.

I hope this helps.

1 Comment

Or even better: document.getElementById("guess_btn").onclick = guessNumber;
0

In this case, if you are wanting to add the events such as "onclick" etc to your javascript file instead of having to have that event coded in only HTMl, you can use an event handler/listener in javascript. Essentially, you set a listener on the object that the action will be performed and then you will handle what to do once that action is performed.

Check out this previous question.

I hope this helps!

Comments

0

No Problem, you first have to access the Elements you want to manipulate. I would recommend using jQuery, it makes DOM-Manipulation way more easy to understand for beginners.

So: get jQuery here and put it in your webserver, so it can be found. Refernce it in your HTML like so:

<script type="application/javascript" src="js/jquery-1.11.2.js"></script>

If you load your javascript-file after jquery, you should have access to the jQuery-Object ($).

(Everything that comes now, should be written in your js-file)

Second order of business: initilaize. To properly initialize your code, you must be sure, that everything on the site is loaded. This is done by waiting for a specific Event (the ready-event wich is bound to document).

$(document).on('ready', function(){
   // here goes the init-code
});

The function inside the on(...)-Statement is called a callback, and is evaluated after the event is triggered.

You can access your elements by the id-attribute. E.g. $('#input_txt') references the input-Elements with the id: 'input_txt'. $ is the jQuery-Object, and '#input_txt' is a so called selector. Selectors can reference Elements unambigously.

Lastly, an this is the thing you really want: Manipulate the Events, bound to your specific Elements. This is done by the jQuery-Method 'on'. We used it, to wait for the document to be in a 'ready'-state. Now we use it to wait for a specific Event on a specific Element.

Everytime you click the Element, a 'click'-Event is triggered. 'keyup' and 'keydown' work equivalently, here the events are triggered if the user pressed or released the keyboard, when the focus is on the Element. Keep in mind: if events are triggered and a callback-function (commonly called a 'Handler' in this context) is bound to it, the according function will be evaluated.

$(document).on('ready', function(){
   $('#input_txt').on('keydown', function({
       limitText(this.form.limitedtextfield,3);
   })
   .on('keyup', function({
       limitText(this.form.limitedtextfield,3);
   });

   $('#guess_btn').on('click', function({
       guessNumber();
   });

   $('#playAgain_btn').on('click', function({
       initGame();
   });
});

1 Comment

"Unless a tag for a framework/library is also included, a pure JavaScript answer is expected."

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.