Giter Club home page Giter Club logo

hideshowpassword's Introduction

hideShowPassword

Because life's too short to waste time re-typing passwords.

Inspired by a pattern seen in Polar, IE 10+ and LinkedIn and documented by Luke W, hideShowPassword lets you easily hide and show passwords via JavaScript or a nifty inset toggle.

The plugin works in any browser that supports resetting the type attribute of <input> elements (pretty much everything newer than IE8). The plugin should fall back gracefully in cases where this is not supported.

Installation

Include the plugin after you've included jQuery:

<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="path/to/hideShowPassword.min.js"></script>

If Modernizr is also included, the plugin's touch enhancements will default to the value of Modernizr.touchevents.

Using npm and Browserify

npm install --save jquery
npm install --save hideshowpassword
var $ = require('jquery');
require('hideshowpassword');

Using Bower

bower install hideshowpassword
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="bower_components/hideShowPassword/hideShowPassword.min.js"></script>

Usage

The plugin acts on <input> elements (typically password fields):

<input id="password" type="password">

Showing, hiding and toggling

You can quickly show, hide or toggle the visibility of the field's contents:

$('#password').showPassword();    // Reveal
$('#password').hidePassword();    // Hide
$('#password').togglePassword();  // Toggle

These are all shorthand versions of the hideShowPassword method:

$('#password').hideShowPassword(true);      // Reveal
$('#password').hideShowPassword(false);     // Hide
$('#password').hideShowPassword('toggle');  // Toggle

Enabling the inner toggle button

The inner toggle functionality tends to steal the show for this plugin. You can pass it along as the second argument of the hideShowPassword method:

// Reveal password by default and create an inner toggle
$('#password').hideShowPassword(true, true);

Or as the first argument of any of the shorthand methods:

// Reveal password by default and create an inner toggle
$('#password').showPassword(true);

If you would like the inner toggle to be hidden until a specific event, you can pass along that event as a string instead:

// Hide the inner toggle till the #password element is focused
$('#password').showPassword('focus');

Specifying more options

Any additional options may be modified by passing along an object as the last argument of any of the aformentioned methods. Here's the previous example, but with a custom class for the toggle:

$('#password').hideShowPassword(true, 'focus', {
  toggle: {
    className: 'my-toggle'
  }
});

In fact, we could pass along all of these arguments as a single object if we want:

$('#password').hideShowPassword({
  show: true,
  innerToggle: 'focus',
  toggle: {
    className: 'my-toggle'
  }
});

There are many options available if your project's needs are particularly unique.

Events

If you need to respond to changes to the password field's visibility, you can use any of the following events:

$('#password')
  .on('hideShowPasswordInit', function(){
    console.log('plugin initialized');
  })
  .on('passwordVisibilityChange', function(){
    console.log('password shown or hidden');
  })
  .on('passwordShown', function(){
    console.log('password shown');
  })
  .on('passwordHidden', function(){
    console.log('password hidden');
  });

Options

Here are all of the available options and their defaults:

.hideShowPassword({
  // Visibility of the password text. Can be true, false, 'toggle'
  // or 'infer'. If 'toggle', it will be the opposite of whatever
  // it currently is. If 'infer', it will be based on the input
  // type (false if 'password', otherwise true).
  show: 'infer',

  // Set to true to create an inner toggle for this input. Can
  // also be sent to an event name to delay visibility of toggle
  // until that event is triggered on the input element.
  innerToggle: false,

  // If false, the plugin will be disabled entirely. Set to
  // the outcome of a test to insure input attributes can be
  // set after input has been inserted into the DOM.
  enable: canSetInputAttribute,

  // Event to trigger whenever the element is toggled.
  // For example, if 'focus' it will focus the cursor in the
  // input element after toggling.
  triggerOnToggle: false,

  // Class to add to input element when the plugin is enabled.
  className: 'hideShowPassword-field',

  // Event to trigger when the plugin is initialized and enabled.
  initEvent: 'hideShowPasswordInit',

  // Event to trigger whenever the visibility changes.
  changeEvent: 'passwordVisibilityChange',

  // Properties to add to the input element.
  props: {
    autocapitalize: 'off',
    autocomplete: 'off',
    autocorrect: 'off',
    spellcheck: 'false'
  },

  // Options specific to the inner toggle.
  toggle: {
    // The element to create.
    element: '<button type="button">',
    // Class name of element.
    className: 'hideShowPassword-toggle',
    // Whether or not to support touch-specific enhancements.
    // Defaults to the value of Modernizr.touchevents if available,
    // otherwise false.
    touchSupport: (typeof Modernizr === 'undefined') ? false : Modernizr.touchevents,
    // Non-touch event to bind to.
    attachToEvent: 'click.hideShowPassword',
    // Event to bind to when touchSupport is true.
    attachToTouchEvent: 'touchstart.hideShowPassword mousedown.hideShowPassword',
    // Key event to bind to if attachToKeyCodes is an array
    // of at least one keycode.
    attachToKeyEvent: 'keyup',
    // Key codes to bind the toggle event to for accessibility.
    // If false, this feature is disabled entirely.
    // If true, the array of key codes will be determined based
    // on the value of the element option.
    attachToKeyCodes: true,
    // Styles to add to the toggle element. Does not include
    // positioning styles.
    styles: { position: 'absolute' },
    // Styles to add only when touchSupport is true.
    touchStyles: { pointerEvents: 'none' },
    // Where to position the inner toggle relative to the
    // input element. Can be 'right', 'left' or 'infer'. If
    // 'infer', it will be based on the text-direction of the
    // input element.
    position: 'infer',
    // Where to position the inner toggle on the y-axis
    // relative to the input element. Can be 'top', 'bottom'
    // or 'middle'.
    verticalAlign: 'middle',
    // Amount by which to "offset" the toggle from the edge
    // of the input element.
    offset: 0,
    // Attributes to add to the toggle element.
    attr: {
      role: 'button',
      'aria-label': 'Show Password',
      title: 'Show Password',
      tabIndex: 0
    }
  },

  // Options specific to the wrapper element, created
  // when the innerToggle is initialized to help with
  // positioning of that element.
  wrapper: {
    // The element to create.
    element: '<div>',
    // Class name of element.
    className: 'hideShowPassword-wrapper',
    // If true, the width of the wrapper will be set
    // unless it is already the same width as the inner
    // element. If false, the width will never be set. Any
    // other value will be used as the width.
    enforceWidth: true,
    // Styles to add to the wrapper element. Does not
    // include inherited styles or width if enforceWidth
    // is not false.
    styles: { position: 'relative' },
    // Styles to "inherit" from the input element, allowing
    // the wrapper to avoid disrupting page styles.
    inheritStyles: [
      'display',
      'verticalAlign',
      'marginTop',
      'marginRight',
      'marginBottom',
      'marginLeft'
    ],
    // Styles for the input element when wrapped.
    innerElementStyles: {
      marginTop: 0,
      marginRight: 0,
      marginBottom: 0,
      marginLeft: 0
    }
  },

  // Options specific to the 'shown' or 'hidden'
  // states of the input element.
  states: {
    shown: {
      className: 'hideShowPassword-shown',
      changeEvent: 'passwordShown',
      props: { type: 'text' },
      toggle: {
        className: 'hideShowPassword-toggle-hide',
        content: 'Hide',
        attr: {
          'aria-pressed': 'true'
          title: 'Hide Password',
        }
      }
    },
    hidden: {
      className: 'hideShowPassword-hidden',
      changeEvent: 'passwordHidden',
      props: { type: 'password' },
      toggle: {
        className: 'hideShowPassword-toggle-show',
        content: 'Show',
        attr: {
          'aria-pressed': 'false',
          title: 'Show Password',
        }
      }
    }
  }

});

You may override these defaults by manipulating the $.fn.hideShowPassword.defaults object:

$.extend(true, $.fn.hideShowPassword.defaults, {
  states: {
    shown: {
      toggle: {
        content: "esconder"
      }
    },
    hidden: {
      toggle: {
        content: "espectáculo"
      }
    }
  }
});

Known Issues

Competing controls in IE10+ (Windows 8)

Internet Explorer 10 introduced its own controls for password and text input fields that sometimes compete with the inner toggle functionality of this plugin. Thankfully, they are easily overwritten using CSS:

::-ms-reveal,
::-ms-clear {
  display: none !important;
}

Error when debugging IE8 or earlier in IE9+ Developer Tools

For some reason the plugin returns a false positive when feature-testing unless honest-to-goodness IE8 or earlier is used.

Toggle quirks in invisible elements

If you use the inner toggle feature on an invisible element, it may not have enough information to correctly style the wrapper and toggle elements. It's recommended that you delay instantiation of the plugin until the elements are visible.

Here's a hypothetical example using a Bootstrap modal:

$('#my-modal').on('shown.bs.modal', function (event) {
  $('#password').showPassword(true);
});

History

  • 2.2.0: Expose defaults for easier overrides (#60, #61)
  • 2.1.0: Add triggerOnToggle feature (#56)
  • 2.0.11: Fix for Bower install on Windows (#44)
  • 2.0.10: Update Modernizr test (#42)
  • 2.0.9: Add title attributes to toggle by default (#41)
  • 2.0.8: Fixing bloated bundles bug (#39)
  • 2.0.7: Fixing inheritStyles bug (#34)
  • 2.0.6: Revising npm package name (#28)
  • 2.0.5: Revising npm package repo URL (#28)
  • 2.0.4: Namespaced events (#20), npm support (#21)
  • 2.0.3: Removed errant console.log call (#13)
  • 2.0.2: className option now instantiates on init (#11)
  • 2.0.1: Fix for missing innerElementStyles
  • 2.0.0: Major rewrite with better accessibility and deeper options
  • 1.0.3: Added wrapperWidth option
  • 1.0.2: Uses deep merge for options
  • 1.0.1: Added AMD support
  • 1.0.0: Voila!

License

Released under the MIT License.

This repository contains other libraries that may or may not fall under the same license:

hideshowpassword's People

Contributors

barryceelen avatar bytestream avatar dlegr250 avatar jeremykenedy avatar kuatsure avatar tylersticka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hideshowpassword's Issues

A CSS requirement

I guess this style is definitely a requirement to the plugin (in order to achieve the same behaviour as the demo).

.hideShowPassword-toggle {
z-index: 3;
}

keep on developing this plugin, is really really great !!

Possibility to use existing wrapper (parent) element

wrapElement method always creates a new "wrapper" element around input.
In some situations it would be great to pass the wrapper element within options and just do initialization like copy all CSS etc.

My use case is that we uses "adaptive placeholders" which requires to have label exactly after input element. Something like this:

<div>
  <input>
  <label>
</div>

Hide Password Toggle on Blur

Howdy Tyler!

Just upgrading to v2... Looks like I can just use the shorthand method .showPassword('focus') to get my desired behavior. However, I cannot seem to find the option for hiding the toggle on the blur event. I'm probably missing something simple. Figured it best to just ask though...

Thx for the great plugin :-)

Password Text Box Size Changes

First, Thanks for this plugin.

I am using it one of my project and it works fine. I am having a little issue which is stopping me to go ahead.

I am having a floating box which accepts username and password. Once this plugin is installed, the size of the password text box changes to small size.

On other pages, this works fine. The issue is only with the floating box.
password

Without this plugin, the size of the password text box is normal as the username.

npm styles

It would be nice if the example stylesheets could be included via npm the same way that the JavaScript file can be. (This would also address the intent behind #14.)

Classes should be in kebab-case

Validation of css to use with this library (via stylelint and stylelint-config-standard) detects the following errora:

 ✖  Expected class selector ".hideShowPassword-toggle" to be kebab-case  selector-class-pattern
 ✖  Expected class selector ".hideShowPassword-field" to be kebab-case   selector-class-pattern

classes should be renamed like ".hide-show-password-toggle" and ".hide-show-password-field"

Bower install fails

At least at Windows machines (haven't tested with others OS, but with multiple Windows machines), the bower install fails as bower.json seems to be a symbolic link with "package.json" text within it. The symbolic link seems to break down for some reason and since the "package.json" isn't exactly valid JSON, the install aborts.

bower hideshowpassword#*                               EMALFORMED Failed to read
<temp path here>\bower.json

Additional error details:
Unexpected token p

Determine solution or official recommendation for autofill issues

The plug in works so well. But it just has a weird issue. When the user name or the password input have not been set up with any value, it will automatically show the browser saved user name and password for the current webpage. Is there a way to not show browser saved user name and password? Thank you
untitled

Auto left and right margins not inherited in Firefox

I have an element with auto left and right margins. In Chrome and other Webkit-based browsers, this is inherited by the wrapper by assigning the margin the calculated pixel value of the left and right margins. In Firefox, the left and right margins are instead inherited as 0px margins.

Rogue console.log

There's a console.log in toggleKeyEvent. Old browsers don't support console.log, though I'm not sure what your list of supported browsers is, so this could be a non-issue.

Uncaught Error: type property can't be changed

Hi,

I'm getting this error just calling the hideShowPassword() function on my jQuery password object.

Looking at your code, it seems that you change the type attribute using .attr() that is not allowed by jQuery. Using .prop() does the trick though.

Use deep merge for options

I wanted to override the labels for the toggle and got strange errors because the other fields in the states hash were missing. You can avoid this by doing a deep merge with $.extend(true, {}, ...

.hideShowPassword-field not added on init

Noticing that when a password field is initialized, class "hideShowPassword-field" is not assigned to the input element. The class is only added after clicking the toggle button for the first time.

Traced it to if (! this.options.enable || this.isType()) return false; in the updateElement function. On init, both evaluate to true.

Is this by design?

Thanks for making your plugin available.

Attach to hover event

Hello, how can i attach hidePassword to hover event? I need show passord on mousedown and hide on mouseup.

Smaller wink image?

I'd like to see a 25% smaller wink image, about the same size as the one in IE11.
image

How to ...

In your demo, the middle one has the password initially shown with a toggle. I want it initially masked, like in IE11 and have the show button showing. I don't see how to do that.

Removing Inline Width On Wrapper

Hi Guys,

Thanks for making this great little plugin! One small issue I have is the inline width on the hideShowPassword-wrapper div. What would be the best way to make the wrapper fluid when using the second example?

Thx!

Rely more on CSS and less on JS for styles

The majority of the issues we receive are related to the styles set via JavaScript on the wrapper and inline toggle. It may be the case that the convenience of this method is outweighed by the risk of breakage introduced.

In an upcoming major-release version with support for smarter importing of styles (see #25) and without a jQuery dependency (see #32), it may make sense to shift that responsibility back to CSS-land.

browserify require is broken when jQuery versions mismatch

Hello,

Just encountered a problem when requiring hideshowpassword using Browserify.

Given that I need to support IE8, jQuery is defined as ^1.11.3 in my package.json.

Since you have also added jQuery as dependency, and that the two versions mismatch, the hideshowpassword function will be attached to your jQuery instance, instead of mine, making it unavailable from my code.

Why jQuery has been added as production dependency, given that the function is attached to $.fn ?

IE8 bug

Hi - was about to write about an IE8 bug, before I started looking into it and realised that older versions of IE throw an error if you change the type property of an input element after creation - so it's unfixable in this incarnation.

It might be worth adding an exception so that the script just disables itself in such browsers, or at least a mention in the docs that IE < 9 throws an error?

Many thanks for releasing the script, it was a great help!

Revise methods of instantiation for consistency

In an effort to make the plugin easy to use for novices and control-freaks alike, the plugin currently uses several shorthand methods as well as shorthand arguments to simplify calling the plugin. This has the unintended side-effect of the documentation being confusing... any one method of calling the plugin is as simple as it can be, but altogether they make the plugin as a whole more confusing.

We should explore consolidating things into one consistent JavaScript API, with possibly something like a data-attribute API for those with simpler needs.

Keyboard accessibility for the hide/show toggle

Love the plugin. The hide/show toggle added to the password field is available to users with a pointer, but not available for keyboard users. Keyboard availability is a key element of accessibility, so it would be good to:

  1. add a tabindex=0 to the toggle div, which will allow tabbing to the hide/show element
  2. add a keypress event handler to allow space or enter to toggle the hide/show status

Multiple Selectors

Sorry for the question again.

I have 2 password text boxes.

I tried the plugin with the wildcard selectors. For me, it works only for the first text box.

$("input[name*=password]").showPassword(true, { wrapper: { enforceWidth: false } });

Please note the * in the selector.

Rendering issue when displayed on a modal form.

Hello.

When I display a form in a modal, the plugin rendering fails somehow.

Screen shot with plugin enabled on a modal dialog:
password-bad

Screen shot with plugin disabled on a modal dialog:
password-good

Screen shot with plugin enabled, without modal dialog:
password-good-no-modal

And here is the initialization function:

// password reveals
$('#' + signupModelID +  '-password').hideShowPassword({
    show: false,
    innerToggle: true,
});

What do you think?

Thanks.

Npm package broken

The NPM package seems to be broken :

npm install hideShowPassword
fetch failed https://registry.npmjs.org/hideShowPassword/-/hideShowPassword-2.0.4.tgz
npm ERR! Error: 404 Not Found

By the way, thanks for the good work. It works very well.

Disable added inline styles

How do I remove the inline styles on hideShowPassword-wrapper and hideShowPassword-field?

I tried adding the style property in the options object, but still the inline styles are added automatically.

Vanilla JS

IE8 and earlier doesn't allow changes to the type attribute of <input> elements, so browser compatibility isn't much of a concern for this script. Because of that, and because this script is intended to improve mobile or touch experiences in particular, it seems feasible to accept that we might not need jQuery for the next version. It may make sense to include a jquery.* version for convenience, but I imagine it could feasibly include the vanilla JS script and use it to instantiate a plugin.

Problem in bootstrap modals

I'm using two tabs based on the bootstrap framework - if the hideShowPassword plugin is called in the tab that's visible on page load, all is fine.

If I'm switching to the second tab, the input gehts shortened and the icon is displayed above it, instead of inside of it. It still works though, just the layout gets messed up.

hideshowpassword

I solved it by overriding the css with:

.hideShowPassword-wrapper { width: 100% }
.hideShowPassword-toggle { margin-top: -19px !important }

jquery dependency in wordpress

I tried using this plugin for a form created by a the ultimate member plugin I included the hideshowPassword plugin in the footer of the page except for the jquery dependency which is already in use througn my functions.php file but it doesnt work and if I add the jquery dependency script in the footer of the page the form completely disapears.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.