What is Unobtrusive Javascript in layman terms? [closed]
Asked Answered
H

1

54

What is Unobtrusive Javascript in layman terms? An example would be nice to aid my understanding.

Hoofbound answered 18/12, 2010 at 16:1 Comment(1)
Wikipedia has good article : en.wikipedia.org/wiki/Unobtrusive_JavaScriptForgat
E
78

Checkout the wikipedia article:

"Unobtrusive JavaScript" is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally understood to include:

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality[2]

So it is basically separating behavior or javascript from presentation or html.

Example:

<input type="button" id="btn" onclick="alert('Test')" />

That is not unobstrusive javascript because behaviour and presentation are mixed. The onclick shouldn't be there in html and should be part of javascript itself not html.

With above example, you can go unobstrusive like this:

<input type="button" id="btn" />

JavaScript:

var el = document.getElementById('btn');
el.onclick = function(){
  alert('Test');
};

That time we have separated javascript from html with a very basic example.

Note:

There is more to unobstrusive javascript as can be checked out on wikipedia article.

Eponymous answered 18/12, 2010 at 16:3 Comment(3)
Thanks for a great example but why is it bad to have onclick="alert('Test') in the html?Hoofbound
@Imran: For a number of reasons if you think about it. For easy portability, easy for others to finds things out, extendibility, etc.Eponymous
That's not a great example, because it fails to provide "Progressive enhancement". If JS doesn't work, then you have a button which does nothing when clicked. To be unobtrusive either the button should be added to the DOM with JS (if the feature it provides is not needed for the page to work) or it should be a submit button with server side code to generate the message as a new page load if the JS fails.Doreendorelia

© 2022 - 2024 — McMap. All rights reserved.