-1

The purpose of converting this is so i can learn how it's done without jquery.

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        //  Focus auto-focus fields
        $('.auto-focus:first').focus();

        //  Initialize auto-hint fields
        $('INPUT.auto-hint, TEXTAREA.auto-hint').focus(function(){
            if($(this).val() == $(this).attr('title')){
                $(this).val('');
                $(this).removeClass('auto-hint');
            }
        });

        $('INPUT.auto-hint, TEXTAREA.auto-hint').blur(function(){
            if($(this).val() == '' && $(this).attr('title') != ''){
                $(this).val($(this).attr('title'));
                $(this).addClass('auto-hint');
            }
        });

        $('INPUT.auto-hint, TEXTAREA.auto-hint').each(function(){
            if($(this).attr('title') == ''){ return; }
            if($(this).val() == ''){ $(this).val($(this).attr('title')); }
            else { $(this).removeClass('auto-hint'); }
        });
    });
</script>
</head>
<body>
<form>
Email: <input type="text" name="email" id="email" title="i.e. me@example.com" class="auto-hint" />
</form>
</body>
</html>

I found this code here: Html placeholder text in a textarea form

Community
  • 1
  • 1
Carl Serl
  • 51
  • 6
  • That jQuery code is of bad quality (just for the record). – Šime Vidas Mar 27 '11 at 19:20
  • Good to know, exactly what is bad with it ? This code is from a tutorial, see link above, so it would be bad if it teaches people wrong ) – Carl Serl Mar 27 '11 at 23:47
  • 1. The same lookup - `$('INPUT.auto-hint, TEXTAREA.auto-hint')` - is done three times in a row, instead of just being chained, 2. `this.value` and `this.title` are faster and more readable than `$(this).val()` and `$(this).attr('title')`, 3. the convention for type selectors is lower-case (`input` instead of `INPUT`), 4. regular comparisons are done with one operand being an empty string (`x == ''`) - regular comparisons should not be performed if one of the operands is a falsy value. Instead strict comparison should be used. Yes, I am afraid that the tutorial teaches bad practices. – Šime Vidas Mar 28 '11 at 00:15
  • By the way, why the down vote ? What could have made this question better ? When down-voting, it is good to tell why, that way we can learn something and improve the questions. – Carl Serl Mar 29 '11 at 15:43
  • My guess: Lack of investment. You have this code from a third-party tutorial and want it to be transformed into non-jQuery code, but you're not investing in this (you haven't shown us that you tried to do this yourself - regardless how poor your JavaScript knowledge is). I personally don't care how much the questioners invest in their questions - I just like to answer JavaScript-related questions in general `:)`. However, some people will down-vote for this reason... – Šime Vidas Mar 29 '11 at 17:16

3 Answers3

2

Here you go:

(function() {
    var clss= 'auto-hint',
        fields = document.getElementsByClassName(clss),
        field;

    for (var i = 0; i < fields.length; i++) {        
        field = fields[i];
        field.value = field.title;

        field.onfocus = function() {
            if (this.value === this.title) {
                this.value = '';
                this.className = '';
            }
        };

        field.onblur = function() {
            if (this.value === '') {
                this.value = this.title;
                this.className = clss;
            }
        };
    }
})();

Live demo: http://jsfiddle.net/pj5tG/


Btw, HTML5 introduces the placeholder attribute. It gets the exact same job done. However, it doesn't work in IE (but it works in Firefox, Chrome, Safari and Opera).

<input type="text" placeholder="Name">

Live demo: http://jsfiddle.net/pj5tG/1/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • +1, but you did gloss over the fact that this code needs to be placed at the end of the body because it is executed when evaluated, not on [`ready`](http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29). – josh3736 Mar 27 '11 at 19:51
  • @josh True. Good observation. `:)` – Šime Vidas Mar 27 '11 at 20:08
  • wow it was less code than i thought and with the jquery removed i now understand it completely, thank you. Just a tiny improvement http://jsfiddle.net/E3H3g/ – Carl Serl Mar 27 '11 at 23:57
  • Btw i did stumble upon 'placeholder' but it doesn't allow you to tweak it. It is handy for what it does but when you want to extend upon it well then you have write something like the code you wrote. – Carl Serl Mar 28 '11 at 00:14
  • @Carl The anonymous function wrapper (which is an IIFE, btw) is used for scope purposes. In my code, the three variables - clss, fields, field - are local variables. I am using the IIFE to avoid polluting the outer namespace (which could be the DOMContentLoaded handler namespace, or even the global namespace). – Šime Vidas Mar 28 '11 at 00:18
  • Ah that is good to know, about my tiny improvement http://jsfiddle.net/E3H3g/ is it ok or are any of these versions better: 1. http://jsfiddle.net/pj5tG/5/ 2. http://jsfiddle.net/pj5tG/6/ – Carl Serl Mar 29 '11 at 15:36
  • @Carl Your original tiny improvement is fine (However, note that IE8 and below doesn't recognize `addEventListener`.) Regarding 1. You don't need the IIFE inside an existing function expression if you're going to wrap the whole function body anyway. IIFE's are used when you have lots of code and you want to perform something in-between that code without having to declare new local/global variables. See here: http://jsfiddle.net/5KCTb/ – Šime Vidas Mar 29 '11 at 17:26
  • Regarding 2. Don't wrap that function in parens - only IIFE's should be wrapped in parens. Also, you don't need that function wrapper inside `addEventListener`. This is OK too: `addEventListener('DOMContentLoaded', test_123, false);` Other than that, this code is equal to your original code - you just placed the function outside of `addEventListener` - do this only if you need to re-use the same function in multiple locations. – Šime Vidas Mar 29 '11 at 17:27
0

Jquery is amazing, if you really wanted to you could cut the code out of their source. But I wouldn't recommend it, jquery is a great tool for js developers, and learning jquery itself is a skill you should know. Also, I don't know what license jquery is under, so you might not be able to distribute/use only sections of their code.

Jess
  • 8,628
  • 6
  • 49
  • 67
  • I would not hack out portions of the jQuery library -- there's really no reason to, and you're highly liable to break something in the process. Also, jQuery is [dual MIT/GPL licensed](http://jquery.org/license). – josh3736 Mar 27 '11 at 19:35
  • You are right, I didn't mean literally hack out parts of the code, but to look at how they did it, instead of reinventing the wheel. – Jess Mar 27 '11 at 19:40
  • 1
    Looking at how jQuery does things is going to be a much harder way to figure out how to do something in javascript, than just researching how to do it in javascript. jQuery is a framework, and the actual bit of javascript that does what happens at the end of the road is going to be buried behind any number of other layers. If you want to figure out how jQuery works, generally, sure look at the code. If you want to learn javascript, that's not a great way to learn javascript. – Jamie Treworgy Mar 27 '11 at 19:53
  • You say it's not a good way to learn javascript but you didn't what he should do instead. Pointing out what he shouldn't do but not saying what he should do instead isn't very useful comment – Carl Serl Mar 28 '11 at 00:02
  • @Jamietre is correct, my answer wasn't as good as it should have been, and a better one is already posted above (Sime's). I assumed the asker wanted to cut out parts of the jquery library, instead of finding code that functioned similar to his jquery example. – Jess Mar 28 '11 at 00:16
0

Doing the same, without using jQuery or similar libraries, you will be required to write much more code. In particular, you will have to do much more work to find the DOM elements represented by the neat CSS selecors INPUT.auto-hint, TEXTAREA.auto-hint etc.

To find the elements matching the selector mentioned above, you will probably want to loop over all input elements in the document – which can be found using the getElementsByTagName method. Then, you will need to have a look at their className, and if a match is found, use getAttribute, setAttribute, etc. to modify the element. Afterwards, do the same for all textarea elements.

At this point, you should start to see a need for a refactoring, extracting the part that locate elements based on type and class. Also, you should now be reconsidering adding jQuery to the mix ;)

Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
  • I know exactly what you are talking about but i have not yet reached that level of java script know how to allow my self to use frameworks. One of the guidelines i follow is: If you can't write it from scratch then you are not allowed to use it until you can write it yourself. A way to prevent myself from being lazy and cheat. – Carl Serl Mar 28 '11 at 00:09