JavaScript - Unobtrusive

javascript

// JavaScript - Unobtrusive JavaScripting:

Unobtrusive JavaScripting is about separating behavior from struture / markup. 
Consider this code:
<button type="button" 
  onclick="document.getElementById('xyz').style.color='red';">Click Me</button>
In the above code, the behavior of the button is located inside the markup / 
structure. It is better to implement this behavior:
<button type="button" id="testButton">Click Me</button>
<script type="text/javascript">
  window.onload = function() {
    document.getElementById('testButton').onclick = makeItRed;
  };
  function makeItRed() {
    document.getElementById('xyz').style.color = 'red';
  }
</script>
Unobtrusive JavaScript is a bit more verbose, and take a bit more work to 
accomplish, but it make the markup much cleaner, and we would run into less 
problem with single quotes and double quotes. Furthermore, we can compress,
minify, and cache the JavaScript code separately, which will lead to less
network bandwidth consumption, and faster page load time.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License