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 Answers 2

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)); 
0
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); 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.