arnoutaertgeerts
arnoutaertgeerts

Reputation: 2322

Event in function JQuery

I'm trying to make a function in jQuery that executes events. My goal is to make a function that puts a message in a field when the pages loads or when the user blanks the field.

$(function () {

  function focusField(id, message) {
    parent = $(this);

    id.color("#C8C8C8");
    id.value(message);

    parent.delegate(id, 'focus', function() {
      if( id.val() == message ) {
        id.val("");
        id.color("black");
      };
    });

    parent.delegate(id, 'keyup', function() {
      if( id.val() == "") {
        id.val(message);
        id.color("#C8C8C8");
      }
    });
  };

  $(".content").focusField($("#emaillogin"), "Email");

This doesn't work cause I think I'm using the concept function wrong. Is there however a way to do it like this? With this I mean if it is possible to make a function then call it on an element but not in an event but call the events in the function.

Normal function use: $element.event(function). I want to bind events in my function to elements if this is possible.

Thanks in advance!

Upvotes: 0

Views: 55

Answers (1)

Kevin B
Kevin B

Reputation: 95057

Yes, you just have to attach your function to the jquery prototype and make a small change:

$(function () {

  $.fn.focusField = function(id, message) {
    return this.each(function(){
      var parent = $(this);

      //id.color("#C8C8C8"); <--- these make no sense, what were they supposed to be doing?
      //id.value(message); <--- these make no sense, what were they supposed to be doing?

      // i don't see a reason to delegate here, just bind to focus event directly.
      parent.delegate(id, 'focus', function() {
        if( id.val() == message ) {
          id.val(""); 
          //id.color("black"); <--- these make no sense, what were they supposed to be doing?
        };
      });

      // i don't see a reason to delegate here, just bind to focus event directly.
      parent.delegate(id, 'keyup', function() {
        if( id.val() == "") {
          id.val(message); 
          //id.color("#C8C8C8"); <--- these make no sense, what were they supposed to be doing?
        }
      });
    }
  }
  $(".content").focusField($("#emaillogin"), "Email");
});

Upvotes: 1

Related Questions