Susan
Susan

Reputation: 33

how to stop a focus() function in javascript after executing once?

I have an input field in html of password type; I created a function that shows the passwords on focus() in the input field. But the problem is I want the function to be executed only one, and next the user can change the input without making the focus() to work every time.

Here is the script: There is a test: it shows a prompt to write the a password in it, then the script checks if the password written is equal to the password of the actual user which is in the session, if yes, then the user can see the password he clicked on it, else he gets an alert to tell him he's not allowed to see passwords.

$('input[class=password]').focus(function(){
               this.type = 'password';
               $pwd=prompt('saisir votre mot de passe');
               if($pwd==='{{ search.password }}') {
                      this.type = 'text';
                     // this.blur();
                   this.off("focus");
                   }
                   else
                   {
                       alert("Vous ne pouvez pas voir les mots de passe!");
                       this.blur();
                   }

               }).blur(function(){
               this.type = "password";
           });

Upvotes: 0

Views: 1786

Answers (3)

synthet1c
synthet1c

Reputation: 6282

You can use jQuery.fn.one to run an event listener only once.

$('input[class=password]').one('focus', function() {
  this.type = 'password';
  $pwd = prompt('saisir votre mot de passe');
  if ($pwd === '{{ search.password }}') {
    this.type = 'text';
    // this.blur();
    this.off("focus");
  } else {
    alert("Vous ne pouvez pas voir les mots de passe!");
    this.blur();
  }
}).blur(function() {
  this.type = "password";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="password" />

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

this is the dom element, not a jQuery object. So to use off() you need to change:

this.off("focus");

To:

$(this).off("focus");

There is also one() which will only execute event handler once:

$('input[class=password]').one('focus', function(){...

Upvotes: 1

Halcyon
Halcyon

Reputation: 57719

You make a function that turns a function into a single use function.

function run_zees_only_wence(func) {
    var ran = false
    return function () {
        if (ran === false) {
            func.apply(this, arguments);
        }
        ran = true;
    };
}

function say_it() {
    console.log("secret");
}

var say_it_only_once = run_zees_only_wence(say_it);

say_it_only_once (); // "secret"
say_it_only_once (); // -nothing-
say_it_only_once (); // -nothing-
// ..

This answer may or may not be inspired by a scene from 'Allo 'Allo.


A more appropriate solution would be to remove the event listener.

Upvotes: 0

Related Questions