Why does jQuery Mobile use data-role attributes instead of classes? - javascript

This may be a naive question, but I'm learning jQuery Mobile and unsure why everything is related to a data-role attribute. It seems that even times when the role is related to the style, they are using data-role over class
I understand that for semantics, data-role makes sense in a lot of cases but it just seems to be abused here. Wouldn't that kind of lookup also be slower?
Why do they use data-role over class?
Thanks for any insight.

Why data
They could simply use role as an attribute (like other frameworks do), but this would make
the resulting HTML invalid. Therefore a data- is added to every attribute name.
Why not classes
I think the main reason for that is to separate view from logic as far as it is possible. In larger projects, CSS and JavaScript are not written by the same person.

It provides a lot of control over powerful styling techniques especially when combined with jquery ui. I use jquery mobile, I used their tool to easily make a theme roller and now when I use elements like data-role-header, footer listview. I have great looking pages with no effort. There are hundreds of data-role attributes you can bring into your code to easily create uniform, user friendly pages. I personally like the data-role - page attribute to create multiple views in a single HTML page. They are easy to use so the best way to learn about them is to play with them.

Please find the explanation of data-roles here.
data-role attribute is used to control the behaviour of the widget of element. For example in case of button you can use input type="button" (no data-role="button" attribute required in this case, as this is standard behaviour of this element) but you can use a element, and then you need to explicitly provide it:
So for me it's rather useful solution, as buttons behavior on mobile devices can be same for different elements. You just need to provide data-role attribute, and jQuery will do the rest for you.
This is the quotation from main jQuery Mobile website:
jQuery mobile framework takes the "write less, do more" mantra to the
next level: Instead of writing unique apps for each mobile device or
OS, the jQuery mobile framework allows you to design a single
highly-branded web site or application that will work on all popular
smartphone, tablet, and desktop platforms.
They want to style every control you have in the same way, so write less, do more approach is fulfilled. So jQuery Mobile adds same styling for all elements with the same role to make things look the same way, but it doesn't mean you can't change it. It just means that they care about good look of your website, and they are aware that every button should be similar to others.
Also the page I mentioned earlier says:
The jQuery Mobile framework uses HTML5 data- attributes to allow for
markup-based initialization and configuration of widgets.
So you are reading HTML and you know how elements will behave without looking to CSS file - which I think is cool if you're not front-end dev. Of course front-end dev can overwrite CSS, but he must follow the rules, e.g. if data-inline is set to true he should style it regarding that elements must naturally follow this rule (be inline).

jQueryMobile adds a load event handler to the page, which processes the DOM looking for various data-xxx attributes. When it finds those, it does more than just stylize the elements.
In many cases it creates a type of widget tied to the data-role. For example, a <div data-role="header"> is turned into a toolbar widget, the creation of which may extensively modify the DOM within that element.
For some of the simpler widgets, like buttons, folks have seen that not much happens other than some classes get added, so why not just shortcut the process and do that directly? That can work, but it isn't future-proof. At different points in history, different versions of jQM had created buttons with different DOM structures. So I personally think it's best not to shortcut jQM, and let it process the data-attributes as it sees fit.
That being said, it would still have been possible to create widgets identified by classes rather than data-attributes, which was how people used to do these things before jQM. But then there might be an expectation that there would be CSS associated with those classes as well. Use of the data- attributes makes it clear that this is a structural/role thing rather than just styling.

Related

Should I be using classes more than ID's when utilizing jQuery?

As a new web developer, I've been utilizing a lot of resources like StackOverflow to assist me in the learning and development process.
When using jQuery, all of the examples/responses that I've come across so far have only referenced classes, like so:
$('.yourClass')
as opposed to
$('#yourID')
Seeing that class referencing seems to be the trend (I honestly haven't found one author who writes a jQuery to an ID), are there any pitfalls I should be aware of for using ID's w/ jQuery or JS in general? Thanks!
EDIT 1: I'm aware that ID's are for single-items, classes are for accessing multiple items. I'm more interested in why I don't see any jQuery or JS examples referencing ID's. Thank you!
You would have to ask each author on a case-by-case basis, but generally when creating examples, the selector used doesn't matter; what's important is that you have a jQuery collection that you can call a method on.
By using a class selector in the example, you avoid newbie developers claiming that your plugin doesn't work when they try to use it on multiple elements with the same ID. Your example serves the purpose of showing how to use it on one or more elements, rather than just one.
People like to use classes because ids have to be unique across the whole page. When trying to make reusable, pluggable components, id's make this impossible to enforce.
Exception: the new web-components standard allows you to encapsulate ids to just your component.
An ID must be unique, you can have only one (like highlanders).
Classes are used to identify a "type" of object not a specific one.
An obligatory car analogy:
An ID is a license plate, unique to one specific thing #345-abc
The class relates to a whole category of things like .truck
Take note that a selector like $(".something") will actually be capable of producing a list of DOM elements; as it will select all DOM elements with the class of "something"
An ID selector $("#unique") will only ever return one element
Think of your HTML and CSS first.
Using Classes
If you have multiple HTML elements which all will look, feel and behave in the same way, then it is highly recommended to use a class to represent their style and behavior.
Example: rows or columns on a table, navigation buttons which animate in the exact same way, wrapper to images which have the same size throughout your website, etc.
Using ID's
However, if you have a unique HTML element which represents a particular thing or state or action in one of your pages, then that element should contain an id.
Example: pop up modal, a unique looking button, unique sections on your website which you can navigate to by their id, etc.
Then, you can use this behavior in your JavaScript and jQuery or whatever else you like to use.
Further reading
I know that you are fully aware of why we should use ID's or classes.
But the vast majority of answers that are given here, are thinking of a project context.
So, let's say editing a .js file that is linked to the scope of the entire project, the idea here is to be as reusable as possible, so that's why you'll see much more classes references than ID's. Is hard to maintain a project js file that makes reference to different ID's that are abroad the project.
Same thing will apply to css.
I hope the answer is enough, be free to post a comment or suggestions. :-)

Should a JQuery plugin be responsible for creating new HTML?

I am not quite sure what the best (or most common practice) is when needing HTML elements for your JQuery plugin to work. For example (although contrived), if you required a spinner (ticker) plugin where you would have text box containing a number and to the left of the box a up and down arrow. When the up arrow is clicked the value is incremented and the value is decremented when the down arrow is clicked.
I see some JQuery plugins, especially the JQuery UI widgets, that expect you to supply all the html and to give them special classes.
In the case of the spinner would you just expect the input tag and then in the JQuery plugin generate the HTML to render the up and down buttons?
Perhaps a better example is something like creating a paging data grid. Would the paging buttons (First, Last, Previous, Next, Page 1, Page 2...) be generated by the plugin or should the user of the plugin be expected to create HTML with special classes.
You should look into jqGrid. It generates a lot of HTML, but it leaves the <table> and pager elements up to you. It then obviously appends to these elements. But it also creates siblings and containers for these elements as well.
For example,
<!-- index.html -->
<table id="mygrid"></table>
<div id="pager"></div>
// main.js
$('#mygrid').jqGrid({pager: '#pager', ...});
jqGrid not only appends to #mygrid and #pager, but also creates new siblings and containers.
<div id="gbox_mygrid">
<div class="ui-jqgrid-view">
<table id="mygrid"><!-- rows --></table>
</div>
<div id="#pager"><!-- stuff --> <?div>
</div>
So you see that jqGrid does what it has to do, to work well. I think it depends on the needs of the plugin.
Generally, I would expect the developer to supply only the container element along with any essential inner elements (think images in a slider). I would expect the plugin to generate any controls like buttons, pagination, etc.
Requiring the developer to supply a container element gives them complete control over how, when, and where your plugin appears on their page, as if it was just another div. Requiring them to also supply any necessary content isn't always necessary, as this could just as easily be a config item.
The main upside I see to having the user supply HTML comes when dealing with clients that don't support/allow JavaScript (think old browsers, spiders, etc). At least they'll see something related to what your plugin was meant to display, rather than just an ugly blank space. In the slider example, if done properly, the plugin can gracefully degrade to a static image in the case of lacking JavaScript support.
All intricacies such as controls and status displays should always be generated by the plugin. Why? User-friendliness is the first thing that comes to mind. People use jQuery plugins because they want a fast, relatively pain-free solution to a problem. Additionally, many users of jQuery plugins are not web developers, but instead are often just administrators of blogs and such.
By eliminating the need for the users of your plugin to have to create elements that they really have no control over, you also eliminate a lot of headaches caused by typos, misunderstandings, and lack of RTFMing.
Hopefully my opinions and insights have been helpful.

How does one properly test a javascript widget?

So, I've written a little javascript widget. All a user has to do is paste a script tag into the page, and right below it I insert a div with all of the content the user has requested.
Many sites do similar things, such as Twitter, Delicious and even StackOverflow.
What I'm curious about is how to test this widget to make sure that it will work properly on everyone's webpage. I'm not using an iframe, so I really want to make sure that this code will work when inserted most places. I know it looks the same in all browsers.
Suggestions? Or should I just build one hundred web pages and insert my script tag and see if it works? I would hope there is an easier way than that.
Once you have confirmed that your javascript works cross-browser in a controlled environment, here are some things that might cause problems when used on an actual website:
CSS
You're using a CSS class that is already being used (for a different purpose) by the target website
You're using positioning that might interfere with the site's CSS
The elements you are using are being styled by the website's CSS (you might want to use some sort of "reset" CSS that applies only to your widget)
HTML
You're creating elements with the same id attribute as an element that already exists on the website
You're specifying a name attribute that is already being used (while name can be used for multiple elements, you may not be expecting that)
Javascript
What is the expected behaviour without Javascript enabled? If your script creates everything, is it acceptable for nothing to be present without JS?
At very basic you should make sure your widget works for following test-cases. I am sure then it will work on all web-pages -
http/https: There should not be any warning for HTTPS pages for unencrypted content.
<script> / <no-script>: What if JavaScript is disabled? Is your widget still visible?
What happens when third-party cookies are disabled? Does your widget still work?
Layout-box restrictions: When parent div element's size is less than your widget. Does your widget overflow the given size and destroys owners page?
By keeping all your Javascripts under a namespace (global object) with a very unique name, you should be pretty much OK. Also, you can simply use an anonymous function if you just want to print out something.
Similar question: How to avoid name clashes in JavaScript widgets

Create your own HTML Textfield with Javascript

I came across the following http://ckeditor.com/demo , and was wondering if anyone had a basic tutorial how to implement this (or perhaps what key search terms I should use)?
Is this just a heavily modified TextField, or have they somehow managed to create a completely new TextField from scratch?
I tried googling this many times, and I always get pages relating to customizing the built-in TextField with CSS etc.
A good place to start if you want to learn how richtext web editors work is to look into the contenteditable attribute and the document.execCommand method (the best editors use a lot more than this, but these are at the foundation). Over-simplified, an editor consists of a contenteditable block and ways to invoke document.execCommand on the text selection.
But, speaking as a person who has actually developed an editor of this kind, you might be better off using an existing one (CKEditor being a great one, in my opinion).
Edit: Note that contenteditable is a proprietary (Microsoft) property, but most (all?) browsers have implemented it now, and it will be in HTML5.
Edit 2: I want to try to clear up a few misconceptions.
A div or iframe isn't in itself editable, it requires the contenteditable attribute. The use of an iframe is typically a workaround for the fact that older Gecko browsers only supported an alternative editable property (designMode) that could only be applied to a whole document.
While some operations of advanced editors probably do employ innerHtml, this isn't the key to making an editor on the web.
It is not a textbox. It is a DIV that has lots of HTML injected to it with javascript.
The basic idea is that JavaScript uses the innerHtml property of the div and writes HTML to it.
This is a javascript implementation that replaces a input. It basically hides the input and uses it for storing and passing the data via POST.
The advanced textfields I have seen have all been iframe or div. The code behind them is quiet messy and not very accessible.
Proceed with caution!
You may want to consider WYSIWYM instead of WYSIWYG.

How to implement an Enterprise-grade JavaScript "framework" for web designers?

I have been tasked with improving the current mess that is our JavaScript "strategy"; we're an online shopping company and my boss has given me time to do this properly. He is very keen on keepin this modular and increase the reusability of the components.
Our HTML is being rendered with JSP and we have lots of custom tags writing out, for example, information about products without the web designers needing to worry about it.
Now, we want to do similar things with JavaScript. The web designers should be given a set of custom tags, like, say,
<foo:draggable>
... some HTML here ...
</foo:draggable>
that will wrap the HTML in a <div> with a drag bar at the top and a close button.
My idea is to mark the div with a unique namespaced CSS class name, like foo_draggable, and then put all my functions in a single JS file. That JS file then sees if there are elements with the CSS class foo_draggable in the DOM and if it finds any it will attach the required event handlers.
However, I am worried about scaling problems, and wondering whether it is a good idea to have lots of selector queries running when they quite often aren't going to be used.
The first alternative would be to initiate each draggable item explicitly but that would mean putting <script> tags all over the place. The second approach would be to not put all UI function in one file but rather just download the ones I need, but that would mean lots more HTTP requests and slower page load speed.
Has anyone got experience with this?
What about having two classnames?
<div class='foo fooDragable'></div>
<div class='foo fooSortable'></div>
You add the class 'foo' to all your elements that require javascript modification.
Your javascript has to check the dom only once for foo.
var $foo = $('.foo');
Afterwards you can search within this array which should be way smaller than the complete dom.
var $dragAble = $foo.filter('.fooDragable');
Have you considered or taken a look to JSF? I know it's a major change if you aren't using JSF yet. But there are lot of ready-to-use JSF component libaries with an ajaxical sauce, for example RichFaces, IceFaces, PrimeFaces, etc. It's almost a waste of time to create components/tags for it yourself.
Alternatively you can replace all Javascripts to use the great jQuery JS framework.
Depending on how many separate components you have, the extra overhead of running the selectors might not be a big deal. You can initialize all the components just the once, when the page is loaded. Anything that's not present on the page simply won't get initialized, and will incur no further overhead. In most JavaScript frameworks, selecting by classname (or tag name) is pretty fast. It's only the complex selectors, which aren't natively supported by the browser, that are slow.
If you have a few commonly used components, and then a set of less commonly used ones, it may be worth splitting those up. Keep the commonly used components in a single JavaScript file (minified, served with compression and aggressive caching), and load that in every page, regardless of whether it's needed or not. Caching will ensure it's only downloaded once, and it'll only be one small HTTP request. For the less common components, keep them in separate files (ideally, one per component), and add a script tag on pages that use them.
I'm not entirely familiar with how JSP works, but it might be possible to do this automatically - if a tag is included in the document, add a script tag for foo_widget.js in the document header, or something like that.

Categories

Resources