Writing Unobtrusive JavaScript - J Query

You have a page with inline event handler attributes creating a hover effect for a menu.Your content (HTML), presentation (CSS), and behavior (JavaScript) are all mixed up,making it hard to maintain each on their own and resulting in duplicate JavaScript and style settings:


Replace inline JavaScript with jQuery event handlers, and add/remove classes instead of manipulating the background Colorstyle directly:

We’ve removed the inline event handlers and replaced them with jQuery event handlers,separating the content and behavior. Now if we want to add more menu items,we don’t have to copy and paste the same batch of event handlers; instead, the event handler will automatically be added.
We have also moved the style rules for the hover effect into a CSS class, separating the behavior and presentation. If we want to change the styling for the hover effect later,we can just update the stylesheet instead of having to modify the markup.

While an “all in one” HTML file with on event attributes works fine in a small, simple page, it does n’t scale up very well. As your pages get more complex, separating presentation and behavior makes the code easier to maintain.
We didn’t do it in this simple example, but if you have multiple pages using the same JavaScript or CSS code, move that code to a common .jsor .cssfile. That way it will be downloaded into the browser cache once, instead of being re-sent on every page load. As a result, once one of your pages has been visited, the rest will load faster.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics