Misters
Misters

Reputation: 1347

how to know input position with javascript

I saw this validation plugin http://demos.usejquery.com/ketchup-plugin/ and i wondered, how can you determinate the position of the input? With that plugin as you could notice, display a message but how does it knows exactly where the input with a error is and put the message exactly there?

Upvotes: 0

Views: 139

Answers (2)

Dzulqarnain Nasir
Dzulqarnain Nasir

Reputation: 2300

The source code for this plugin, specifically the one for the error message container looks like this:

createErrorContainer: function(form, el) {      
  if(typeof form == 'function') {
    this.defaults.createErrorContainer = form;
    return this;
  } else {
    var elOffset = el.offset();

    return $('<div/>', {
             html   : '<ul></ul><span></span>',
             'class': 'ketchup-error',
             css    : {
                        top : elOffset.top,
                        left: elOffset.left + el.outerWidth() - 20
                      }
           }).appendTo('body');
  }
},

So as you can see, it's using the .offset() method to fetch the position of the input fields in relation to the document.

More info here: http://api.jquery.com/offset/

Upvotes: 2

Luke
Luke

Reputation: 14128

After you get the element (possibly by id), in raw JavaScript:

element.offsetLeft
element.offsetTop

Or with jQuery's cross-browser .offset() function.

For validation Html5 does this already. You don't really need to do validation with Javascript. There are also pollyfills available that fill in support for html5 form validation when a browser doesn't support it.

Upvotes: 1

Related Questions