0

In the code below, the first alert() fires, but the second one never fires when I click the textfield assigned with the 'clear' class.

Does anyone have a clue why this happens?

(function ($){

   alert('TEST 1');
   var clearMePrevious = '';

   // Clear input on focus.
   (function ($)('.clear').focus(function() {
     alert('TEST 2');
     /*
      if ($(this).val() == $(this).attr('title')) {
        clearMePrevious = $(this).val();
        $(this).val('');
      }
      */
    }(jQuery));

}(jQuery));    

The problem is just in the inner code, as $document.ready() fires the TEST 1 alert.

I have tried different variations of (function ($){}); and function (jQuery){});.

2

Your formatting made me twitch, so I fixed it up for you.

Drupal JS Coding Standards

Also you weren't using a behavior, so I fixed that too:

Javascript in D7

(function ($) {
  Drupal.behaviors.textFieldClearer = {
    attach: function (context, settings) {
      var clearMePrevious = '';

      // clear input on focus
      $('.clear').focus(function() {
        if($(this).val() == $(this).attr('title')) {
          clearMePrevious = $(this).val();
          $(this).val('');
        }
      });

      // if field is empty afterward, add text again
      $('.clear').blur(function() {
        if($(this).val() == '') {
          $(this).val(clearMePrevious);
        }
      });
    }
  };
}(jQuery));
1

It turns out I misunderstood the documentation: $ is accessible inside a (function ($){} block. The trick is that you really need to add the $(document).ready() call to have the selectors accessible after the page loads.

(function ($) {
  $(document).ready(function() {
    var clearMePrevious = '';

    // clear input on focus
    $('.clear').focus(function()
    {
        if($(this).val()==$(this).attr('title'))
        {
            clearMePrevious = $(this).val();
            $(this).val('');
        }
    });
    // if field is empty afterward, add text again
    $('.clear').blur(function()
    {
        if($(this).val()=='')
        {
            $(this).val(clearMePrevious);
        }
    });
  });
})(jQuery);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.