To be specific, I'm talking about avoiding this type of code:
<input type='text' id='title_33' class='title'
onfocus='updateCharsLeft(33);'
onkeypress='updateCharsLeft(33);' />
Here I would like to put the onfocus
and onkeypress
event handles separately, i.e in a .js file. Like this:
$(document).ready(function()
{
$(".title").focus(updateCharsLeft);
$(".title").keypress(updateCharsLeft);
);
However here the problem is that the ID of the textbox needs to be passed onto the function updateCharsLeft()
. It would suck to have to extract out the id from the ID of the textbox in that function, so it would actually be cleaner to just put in the event handlers within the HTML code.
Thoughts?
JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
html file does not execute JavaScript. A browser will render HTML, and in doing so interpret and execute any JavaScript it encounters. Really, it is the browser that is necessary for JavaScript to execute in the context of HTML.
You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.
In case all html pages use separate javascript files, its better to keep them separate. Based on users action they will be cached on browser end.
Can't you do this:
$(document).ready(function()
{
$(".title").focus(function() {
updateCharsLeft(this.id);
});
$(".title").keypress(function() {
updateCharsLeft(this.id);
});
);
or more neatly:
$(document).ready(function()
{
$(".title .another .someother .andAnother").focus(function() {
updateCharsLeft(this.id);
}).keypress(function() {
updateCharsLeft(this.id);
});
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With