Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it impossible to separate javascript from HTML?

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?

like image 963
Ali Avatar asked Jul 08 '09 11:07

Ali


People also ask

Can I write JavaScript both within HTML and also as a separate file?

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.

Is JavaScript always in HTML?

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.

Can JavaScript be in a separate file?

You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.

Does each HTML page need its own JS file?

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.


1 Answers

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);
    });
);
like image 179
karim79 Avatar answered Oct 21 '22 07:10

karim79