简体   繁体   中英

Floating Label and Javascript Toggle Issues with HTML and CSS

I have found a Floating Label script at CSSScript that is a fit for an upcoming project, but I' having issues decoupling the JS from the HTML that toggle the CSS style.

Here's the JSFiddle DEMO so you can understand the scenario.

Here's just a small portion of the JS script that performs the toggle between the "Styles". There's also a major JS component in the referred demo link above that handles the Styles.

new FloatLabels('.form-1', {
  style: 1
});
document.querySelectorAll('input[name="style"]').forEach(function(el) {
  el.addEventListener('change', function(ev) {
    var form = ev.target.closest('form');
    form.className = form.className.replace(/\b fl-style-\d\b/g, '') + ' ' + 
ev.target.value;
  }, false);
});

Here's the HTML form where the CSS Styles are picked from:

<form class="form-1">
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
    <div class="row">
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
        <label for="firstnamelabel">First Name</label>
        <input type="text" id="firstnamelabel" placeholder="First Name" value="" required />
      </div>
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
        <label for="lastnamelabel">Last Name</label>
        <input type="text" id="lastnamelabel" placeholder="Last Name" value="" required />
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12 col-sm-12 col-md-12">
        <label for="commentslabel">Enter some content</label>
        <textarea id="commentslabel" placeholder="Comments" rows="4" autocomplete="off" required></textarea>
        <label for="select-1">Select an option</label>
        <select id="select-1" class="required" required>
          <option value="1">Option 1</option>
          <option value="2">Option 2</option>
          <option value="3">Option 3</option>
        </select>
      </div>
    </div>
  </div>
  <input type="radio" name="style" id="style-0" value="fl-style-0" />
  <label for="style-0">Default Style</label>
  <input type="radio" name="style" id="style-1" value="fl-style-1" checked />
  <label for="style-1">Style 1</label>
  <input type="radio" name="style" id="style-2" value="fl-style-2" />
  <label for="style-2">Style 2</label>
  <button type="reset" class="button large">Reset</button>
  <button type="submit" class="button large">Submit</button>
</form>

At the bottom of the form you can toggle between the CSS styles (Default, Style 1 & Style 2), which works great.

The issue is that on my mockup I can't have the options available to the User. I need to demonstrate the Floating Label capabilities so stakeholders can decide which style suits their liking, but I can't seem to find a way to decouple the js toggling and set a style once the stakeholders have chosen between Style 1 or Style 2.

Ideal solution: I need to be able to set the css style after stakeholders choose Style 1 or Style 2. Obviously I need to maintain all the features associated with the chosen style.

Can anyone help with this issue? I would really appreciate any help!

The JavaScript logic for determining styles is at the bottom of the JS section in your fiddle.

//STYLES TOGGLE
new FloatLabels('.form-1', {
  style: 1
});
document.querySelectorAll('input[name="style"]').forEach(function(el) {
  el.addEventListener('change', function(ev) {
    var form = ev.target.closest('form');
    form.className = form.className.replace(/\b fl-style-\d\b/g, '') + ' ' + ev.target.value;
  }, false);
});

If you don't want the behavior to be toggling, you can remove the bottom block (the part that starts with document.querySelectorAll(...) ) and just leave the following:

new FloatLabels('.form-1', {
  style: 1
});

The '.form-1' will be the CSS selector for the form you're wanting to activate the library for, and the style property will determine which of the two styles you want to use.

If you want to really consolidate things, you could also remove unneeded CSS as well, although it sounds like your client hasn't decided which style they like yet, so it's nothing you'll need to worry about yet. :)

When you do need to remove the unneeded CSS, let's suppose that your client chose style 1: you can then go through you're CSS and remove the rules that start with .fl-form.fl-style-2 , since the it looks like the only change the JS makes to switch styles is just switching a class on the <form> element.

This is working example of float labels please review and let me know your feedback. https://plnkr.co/edit/79G0zsRnkwuH6BQWDdm6?p=preview

index.html

<!doctype html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Float Labels by Gemini Labs</title>
    <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' type='text/css'>
    <link rel="stylesheet" href="demo/css/styles.css">
  </head>
  <body>
    <main class="main-content">

      <section class="section">
        <h2>Demo</h2>

        <form class="form-1">
          <label for="input-1">Enter a title</label>
          <input type="text" id="input-1" placeholder="Input" value="" required/>

          <label for="textarea-1">Enter some content</label>
          <textarea id="textarea-1" placeholder="Textarea" rows="4" autocomplete="off" required></textarea>

          <label for="select-1">Select an option</label>
          <select id="select-1" class="required">
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
          </select>

          <input type="radio" name="style" id="style-0" value="0"/>
          <label for="style-0">Default Style</label>

          <input type="radio" name="style" id="style-1" value="1" checked/>
          <label for="style-1">Style 1</label>

          <input type="radio" name="style" id="style-2" value="2"/>
          <label for="style-2">Style 2</label>

          <div class="button-group">
            <button type="button" class="button large fl-toggle">Toggle Float Labels</button>
            <button type="reset" class="button large secondary">Reset form</button>
          </div>
        </form>
      </section>
       </main>
    <script src="src/float-labels.js"></script>
    <script src="demo/js/script.js"></script>
  </body>
</html>

css/style.css

@-ms-viewport{width:device-width}html{font-size:100%;line-height:1.5em;-ms-overflow-style:scrollbar;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;box-sizing:border-box;-webkit-font-feature-settings:"liga" 1,"dlig" 1,"kern" 1;font-feature-settings:"liga" 1,"dlig" 1,"kern" 1;-webkit-font-kerning:normal;font-kerning:normal;-webkit-font-variant-ligatures:common-ligatures;font-variant-ligatures:common-ligatures;text-rendering:optimizeLegibility}@media print{html{font-size:12pt}}*,:after,:before{box-sizing:inherit}*{-webkit-overflow-scrolling:touch;outline:0}article,aside,figcaption,figure,footer,header,main,nav,section{display:block}[role=button],a,area,button,input,label,select,summary,textarea{-ms-touch-action:manipulation;touch-action:manipulation}audio,img,video{max-width:100%}img,video{height:auto}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}img{border-style:none}canvas{display:inline-block}svg{max-height:100%}svg:not(:root){overflow:hidden}iframe{border:none}table{border-collapse:collapse}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}input[type=checkbox],input[type=radio]{box-sizing:border-box;font-size:112.5%;margin-right:3px}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{resize:vertical;overflow:auto}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}[tabindex="-1"]:focus{outline:none!important}[hidden]{display:none!important}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;white-space:normal}::-moz-focus-inner{border:0;padding:0}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none;outline:0}body{margin:0 auto;font-family:Open Sans,sans-serif;color:#424242}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:Open Sans,sans-serif;letter-spacing:-.03125em;margin:0 0 1.5rem;color:#212121}.h1,h1{font-size:1.77687rem}.h1,.h2,h1,h2{line-height:1.5rem;font-weight:700}.h2,h2{font-size:1.60181rem}.h3,h3{font-size:1.125rem}.h3,.h4,h3,h4{line-height:1.5rem;font-weight:700}.h4,h4{font-size:1rem}.h5,h5{font-size:1.333rem}.h5,.h6,h5,h6{line-height:1.5rem;font-weight:700}.h6,h6{font-size:1.125rem;text-transform:uppercase}blockquote,ol,p,pre,table,ul{margin:0 0 1.5rem}p{font-size:1rem;line-height:1.5rem}blockquote{position:relative;line-height:2.25rem;padding:.75rem 1.5rem}blockquote p{margin:0;font-size:1.125rem}cite{display:block}small{font-size:.88887rem;line-height:1}ol ol,ol ul,ul ol,ul ul{margin:0}dd{margin:0 0 .75rem}dt{font-weight:700}sub,sup{position:relative;line-height:0;vertical-align:baseline;font-size:.88887rem}sub{bottom:-.1875rem}sup{top:-.375rem}abbr[title]{border-bottom:.1em dotted currentColor;cursor:help}code,kbd{padding:2px 4px;line-height:1}code,kbd,pre{border-radius:3px}pre{display:block;word-wrap:normal;overflow:scroll;-webkit-overflow-scrolling:touch;padding:.375rem .75rem;margin-bottom:1.5rem}pre code{padding:0;word-break:normal;white-space:pre}.button{background-color:#212121;border-color:#212121}.button i{margin-right:.1875rem}form{font-family:Open Sans,sans-serif;letter-spacing:-.03125em;margin:0 0 1.5rem}fieldset{position:relative;display:block;border:0 solid currentColor;padding:0;margin:0}legend{position:absolute;top:-24px;left:-1px;font-weight:400}label,legend{padding:0;font-size:.88887rem}label{display:inline-block;vertical-align:top;cursor:pointer;line-height:1.5rem}input,select,textarea{display:block;width:100%;outline:none;background-color:transparent;border:solid currentColor;border-radius:3px;font-size:.88887rem;line-height:1.5rem;padding:.375rem .75rem;border-width:1px;margin-top:-.0625rem;margin-bottom:1.4375rem}input:-moz-placeholder,input::-moz-placeholder,select:-moz-placeholder,select::-moz-placeholder,textarea:-moz-placeholder,textarea::-moz-placeholder{color:rgba(0,0,0,.5)}input:-ms-input-placeholder,select:-ms-input-placeholder,textarea:-ms-input-placeholder{color:rgba(0,0,0,.5)}input::-webkit-input-placeholder,select::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:rgba(0,0,0,.5)}input:active,input:focus,select:active,select:focus,textarea:active,textarea:focus{border-color:#212121}select{height:2.375rem}textarea{height:6.875rem}input[type=date],input[type=number],input[type=search]{box-sizing:border-box;-webkit-appearance:textfield;-moz-appearance:textfield;appearance:textfield}input[type=checkbox],input[type=radio]{display:inline-block;position:relative;top:-1px;width:auto;padding:0;margin:0}input[type=checkbox]+label,input[type=radio]+label{display:inline-block;width:auto;padding:0;line-height:1.5rem;margin:0 1.5rem 1.5rem .1875rem}@font-face{font-family:Icons;font-style:normal;font-weight:400;src:url("data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMg8SBfgAAAC8AAAAYGNtYXAXVtKOAAABHAAAAFRnYXNwAAAAEAAAAXAAAAAIZ2x5ZsMn2SAAAAF4AAADeGhlYWQMP9EUAAAE8AAAADZoaGVhB8IDzQAABSgAAAAkaG10eCYABd4AAAVMAAAAMGxvY2EFWASu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vTW9vbi4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==") format("truetype")}[class*=" icon-"]:before,[class^=icon-]:before{top:1px;font-family:Icons!important;font-style:normal;font-variant:normal;font-weight:400;line-height:1;speak:none;text-transform:none}
.fl-form .fl-wrap,[class*=" icon-"]:before,[class^=icon-]:before{position:relative;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}.fl-form .fl-wrap{text-rendering:optimizeLegibility}.fl-form input.fl-input,.fl-form select.fl-select,.fl-form textarea.fl-textarea{width:100%;outline:0;font-size:16px;line-height:1.5;border-radius:3px;border:1px solid #dfdfdf;background-color:#fff;box-sizing:border-box;transition:all .2s ease-in-out;margin-bottom:1.4375rem}.fl-form input.fl-input:-moz-placeholder,.fl-form input.fl-input::-moz-placeholder,.fl-form select.fl-select:-moz-placeholder,.fl-form select.fl-select::-moz-placeholder,.fl-form textarea.fl-textarea:-moz-placeholder,.fl-form textarea.fl-textarea::-moz-placeholder{color:#bbb}.fl-form input.fl-input:-ms-input-placeholder,.fl-form select.fl-select:-ms-input-placeholder,.fl-form textarea.fl-textarea:-ms-input-placeholder{color:#bbb}.fl-form input.fl-input::-webkit-input-placeholder,.fl-form select.fl-select::-webkit-input-placeholder,.fl-form textarea.fl-textarea::-webkit-input-placeholder{color:#bbb}.fl-form select.fl-select{position:relative;color:#bbb;cursor:pointer;-webkit-appearance:none;-moz-appearance:none}.fl-form .fl-is-active input.fl-input,.fl-form .fl-is-active select.fl-select,.fl-form .fl-is-active textarea.fl-textarea{color:#444;background-color:#fff;border-color:#dfdfdf}.fl-form .fl-has-focus input.fl-input,.fl-form .fl-has-focus select.fl-select,.fl-form .fl-has-focus textarea.fl-textarea{background-color:#fff;border-color:#1976d2}.fl-form label.fl-label{opacity:0;visibility:hidden;display:block;position:absolute;top:-12px;left:0;font-size:12px;font-weight:400;line-height:1;color:#bbb;border-radius-top-left:3px;transition:all .2s ease-in-out;z-index:1}.fl-form .fl-is-active label.fl-label{opacity:1;visibility:visible}.fl-form .fl-has-focus label.fl-label{color:#1976d2}.fl-form .fl-is-required:before{opacity:1;content:"*";display:block;position:absolute;top:1px;right:15px;font-size:16px;line-height:1.75;color:#d32f2f;transition:all .2s ease-in-out;padding:6px 0 0;z-index:1}.fl-form .fl-is-required.fl-is-active:before{opacity:0}.fl-form.fl-style-1 input.fl-input,.fl-form.fl-style-1 select.fl-select,.fl-form.fl-style-1 textarea.fl-textarea{padding:6px 12px}.fl-form.fl-style-1 select.fl-select{height:38px}.fl-form.fl-style-1 .fl-is-active input.fl-input,.fl-form.fl-style-1 .fl-is-active select.fl-select,.fl-form.fl-style-1 .fl-is-active textarea.fl-textarea{padding:6px 12px}.fl-form.fl-style-1 label.fl-label{top:1px;left:10px;background-color:transparent;padding:12px 3px}.fl-form.fl-style-1 label.fl-label:before{content:"";display:block;position:absolute;top:19px;left:0;right:0;height:1px;background-color:#fff;z-index:-1}.fl-form.fl-style-1 .fl-is-active label.fl-label{top:-9px;padding:3px}.fl-form.fl-style-1 .fl-is-active label.fl-label:before{top:9px}.fl-form.fl-style-2 input.fl-input,.fl-form.fl-style-2 select.fl-select,.fl-form.fl-style-2 textarea.fl-textarea{padding:12px}.fl-form.fl-style-2 select.fl-select{height:50px}.fl-form.fl-style-2 .fl-is-active input.fl-input,.fl-form.fl-style-2 .fl-is-active select.fl-select,.fl-form.fl-style-2 .fl-is-active textarea.fl-textarea{padding:18px 12px 6px}.fl-form.fl-style-2 label.fl-label{top:1px;left:10px;padding:6px 3px 3px}.fl-form.fl-style-2 .fl-is-required:before{padding-top:12px}.fl-form .fl-wrap-select:after{content:"";position:absolute;display:block;top:1px;right:6px;height:calc(100% - 2px);width:12px;background:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 16'><path fill='#bbb' d='M 4 0 L 0 6.5 L 8 6.5 L 4 0 z M 0 9.5 L 4 16 L 4 16 L 8 9.5 z'/></svg>") no-repeat;background-position:100% 50%;background-size:7px 14px;z-index:2}a{color:#1565c0;text-decoration:none}a:hover{text-decoration:underline}blockquote{border-left:4px solid #eceff1;color:#455a64}blockquote p{font-size:.88887rem}blockquote p:not(:last-child){margin-bottom:.75rem}blockquote pre{margin-bottom:0}code{font-size:1rem;border-radius:3px;background-color:#eceff1;text-shadow:1px 1px 0 hsla(0,0%,100%,.75)}pre{line-height:1.5rem;font-weight:200;background-color:#263238}pre code{font-size:.88887rem;color:#dcedc8;text-shadow:1px 1px 0 rgba(33,33,33,.25);background:none}.page-header{padding:3rem 1.5rem;background-color:#263238;text-align:center}@media screen and (min-width:42em){.page-header{padding:3rem 4.5rem}}@media screen and (min-width:50em){.page-header{padding:6rem 4.5rem}}.page-header .button{background-color:rgba(69,90,100,.3);font-size:1rem;padding:.75rem 1.5rem;margin:1.125rem 0 0}.page-header .button,.page-header .button:hover{color:hsla(0,0%,100%,.7);border-color:transparent}.page-header .button:hover{background-color:rgba(69,90,100,.5)}.page-header .button:active{background-color:rgba(69,90,100,.7)}@media screen and (min-width:35em){.page-header .button{margin:1.125rem .375rem 0}}.page-footer{max-width:52em;margin:0 auto;padding:1.5rem}.page-footer p:first-child{position:relative;top:1px;font-weight:700;border-top:1px solid #eceff1;margin:-2px 0 0;padding-top:1.5rem}.main-content{max-width:52em;margin:0 auto;padding:2.25rem 1.5rem 0}.section ul{line-height:1.875rem}.section:not(:last-child){margin-bottom:3rem}.project-name{color:#fff}@media screen and (min-width:42em){.project-name{font-size:2.36856rem;line-height:3rem}}@media screen and (min-width:50em){.project-name{font-size:3.15731rem}}.project-tagline{color:hsla(0,0%,100%,.5);font-weight:400;font-size:1rem;margin-bottom:1.5rem}@media screen and (min-width:42em){.project-tagline{font-size:1.333rem;line-height:3rem;line-height:2.25rem}}.badge{display:inline-block;line-height:2.25rem;margin-bottom:1.5rem}.badge img{height:1.5rem}.button{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Open Sans,sans-serif;font-size:1rem;line-height:1.375rem;padding:.375rem 1.125rem;margin-bottom:1.5rem;position:relative;display:inline-block;text-align:center;cursor:pointer;border:1px solid transparent;border-radius:3px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:top;color:#fff;background-color:#1565c0;border-color:#1565c0;transition:color .125s ease-in-out,background-color .125s ease-in-out,border-color .125s ease-in-out}.button,.button:hover{text-decoration:none;outline:none}.button.disabled,.button[disabled]{opacity:.7;cursor:default}.button-group{display:inline-block;vertical-align:bottom}.button-group .button{float:left;z-index:1}.button-group .button:focus,.button-group .button:hover{z-index:2}.button-group .button.active,.button-group .button:active{z-index:3}.button-group .button:first-child{border-radius:3px 0 0 3px}.button-group .button:last-child{border-radius:0 3px 3px 0}.button-group .button:not(:first-child):not(:last-child){border-radius:0}.button-group .button:not(:first-child){margin-left:-1px}.button:hover{background-color:#104d92;border-color:#104d92}.button.active,.button:active{background-color:#0b3564;border-color:#0b3564}.button.disabled,.button[disabled]{color:#fff;background-color:#1565c0;border-color:#1565c0}.button:not([disabled]):not(.disabled):active{-webkit-transform:translate3d(0,1px,0);transform:translate3d(0,1px,0)}.button.secondary{color:#fff;background-color:#424242;border-color:#424242}.button.secondary:hover{background-color:#292929;border-color:#292929}.button.secondary.active,.button.secondary:active{background-color:#0f0f0f;border-color:#0f0f0f}.button.secondary.disabled,.button.secondary[disabled]{color:#fff;background-color:#424242;border-color:#424242}.button-group{display:block;margin-bottom:1.5rem}.button-group:after{content:"";display:table;clear:both}:not(.button-group)>.button{width:100%}@media screen and (min-width:35em){:not(.button-group)>.button{width:auto}}form .button{display:block;margin:0}

src/float-label.js

;(function( window, document, undefined ) { "use strict";

        var Plugin = function( el, options )
        {
            this.el = this.isString( el ) ? document.querySelectorAll( el ) : [el];
            this.config = [];
            this.options = options;
            this.selectors = [];
            this.init();
            this.destroy = function() {
                this.loop( function( el ) {
                    el.removeEventListener( 'reset', this.events.reset );
                    this.removeClasses( el );
                }, function( field ) {
                    this.reset( field );
                });
            };
            this.rebuild = function() {
                this.loop( null, function( field ) {
                    this.floatLabel( field, true );
                });
            };
        };

        Plugin.prototype = {

            defaults: {
                customEvent: null,
                customLabel: null,
                customPlaceholder: null,
                exclude: '.no-label',
                inputRegex: /email|number|password|search|tel|text|url/,
                prefix: 'fl-',
                prioritize: 'label', // label|placeholder
                requiredClass: 'required',
                style: 0, // 0|1|2
                transform: 'input,select,textarea'
            },

            /** @return void */
            init: function()
            {
                this.initEvents();
                this.loop( function( el, i ) {
                    var style = this.config[i].style;
                    el.addEventListener( 'reset', this.events.reset );
                    el.classList.add( this.prefixed( 'form' ));
                    if( style ) {
                        el.classList.add( this.prefixed( 'style-' + style ));
                    }
                }, function( field ) {
                    this.floatLabel( field );
                });
            },

            /** @return void */
            initEvents: function()
            {
                this.events = {
                    blur: this.onBlur.bind( this ),
                    change: this.onInput.bind( this ),
                    focus: this.onFocus.bind( this ),
                    input: this.onInput.bind( this ),
                    reset: this.onReset.bind( this ),
                };
            },

            /** @return string */
            addRemove: function( bool )
            {
                return bool ? 'add' : 'remove';
            },

            /** @return null|void */
            build: function( el )
            {
                var labelEl = this.getLabel( el );
                if( !labelEl )return;
                el.classList.add( this.prefixed( el.tagName.toLowerCase() ));
                this.setLabel( labelEl, el );
                this.setPlaceholder( labelEl, el );
                this.wrapLabel( labelEl, el );
                this.handleEvents( el, 'add' );
                if( typeof this.config[this.current].customEvent === 'function' ) {
                    this.config[this.current].customEvent.call( this, el );
                }
            },

            /** @return Element */
            createEl: function( tag, attributes )
            {
                var el = ( typeof tag === 'string' ) ? document.createElement( tag ) : tag;
                attributes = attributes || {};
                for( var key in attributes ) {
                    if( !attributes.hasOwnProperty( key ))continue;
                    el.setAttribute( key, attributes[key] );
                }
                return el;
            },

            /** @return object */
            extend: function()
            {
                var args = [].slice.call( arguments );
                var result = args[0];
                var extenders = args.slice(1);
                Object.keys( extenders ).forEach( function( i ) {
                    for( var key in extenders[i] ) {
                        if( !extenders[i].hasOwnProperty( key ))continue;
                        result[key] = extenders[i][key];
                    }
                });
                return result;
            },

            /** @return null|void */
            floatLabel: function( el, rebuild )
            {
                if( !el.getAttribute( 'id' ) || (
                    el.tagName === 'INPUT' && !this.config[this.current].inputRegex.test( el.getAttribute( 'type' ))
                ))return;
                if( this.hasParent( el )) {
                    if( rebuild !== true )return;
                    this.reset( el );
                }
                this.build( el );
            },

            /** @return string|false */
            getLabel: function( el )
            {
                var label = 'label[for="' + el.getAttribute( 'id' ) + '"]';
                var labelEl = this.el[this.current].querySelectorAll( label );
                // check for multiple labels with identical 'for' attributes
                if( labelEl.length > 1 ) {
                    labelEl = el.parentNode.querySelectorAll( label );
                }
                if( labelEl.length === 1 ) {
                    return labelEl[0];
                }
                return false;
            },

            /** @return string */
            getLabelText: function( labelEl, el )
            {
                var labelText = labelEl.textContent.replace( /[*:]/g, '' ).trim();
                var placeholderText = el.getAttribute( 'placeholder' );
                if( !labelText || ( labelText && placeholderText && this.config[this.current].prioritize === 'placeholder' )) {
                    labelText = placeholderText;
                }
                return labelText;
            },

            /** @return void */
            handleEvents: function( el, action )
            {
                var events = this.events;
                ['blur','input','focus'].forEach( function( event ) {
                    if( el.type === 'file' && event === 'input' ) {
                        event = 'change';
                    }
                    el[ action + 'EventListener']( event, events[event] );
                });
            },

            /** @return bool */
            hasParent: function( el )
            {
                return el.parentNode.classList.contains( this.prefixed( 'wrap' ));
            },

            /** @return bool */
            isString: function( str ) {
                return Object.prototype.toString.call( str ) === "[object String]";
            },

            /** @return void */
            loop: function( elCallback, fieldCallback ) {
                for( var i = 0; i < this.el.length; ++i ) {
                    if( typeof this.selectors[i] === 'undefined' ) {
                        var config = this.extend( {}, this.defaults, this.options, this.el[i].getAttribute( 'data-options' ));
                        var exclude = ':not(' + config.exclude.split( /[\s,]+/ ).join( '):not(' ) + ')';
                        this.selectors[i] = config.transform.replace( /,/g, exclude + ',' ) + exclude;
                        this.config[i] = config;
                    }
                    var fields = this.el[i].querySelectorAll( this.selectors[i] );
                    this.current = i;
                    if( typeof elCallback === 'function' ) {
                        elCallback.call( this, this.el[i], i );
                    }
                    for( var x = 0; x < fields.length; ++x ) {
                        if( typeof fieldCallback === 'function' ) {
                            fieldCallback.call( this, fields[x], i );
                        }
                    }
                }
            },

            /** @return void */
            onBlur: function( ev )
            {
                ev.target.parentNode.classList.remove( this.prefixed( 'has-focus' ));
            },

            /** @return void */
            onInput: function( ev )
            {
                ev.target.parentNode.classList[
                    this.addRemove( ev.target.value.length )
                ]( this.prefixed( 'is-active' ));
            },

            /** @return void */
            onFocus: function( ev )
            {
                ev.target.parentNode.classList.add( this.prefixed( 'has-focus' ));
            },

            /** @return void */
            onReset: function()
            {
                setTimeout( this.resetFields.bind( this ));
            },

            /** @return string */
            prefixed: function( value )
            {
                return this.config[this.current].prefix + value;
            },

            /** @return void */
            removeClasses: function( el )
            {
                var prefix = this.config[this.current].prefix;
                var classes = el.className.split( ' ' ).filter( function( c ) {
                    return c.lastIndexOf( prefix, 0 ) !== 0;
                });
                el.className = classes.join( ' ' ).trim();
            },

            /** @return null|void */
            reset: function( el )
            {
                var parent = el.parentNode;
                if( !this.hasParent( el ))return;
                var fragment = document.createDocumentFragment();
                while( parent.firstElementChild ) {
                    var childEl = parent.firstElementChild;
                    this.removeClasses( childEl );
                    fragment.appendChild( childEl );
                }
                parent.parentNode.replaceChild( fragment, parent );
                this.resetPlaceholder( el );
                this.handleEvents( el, 'remove' );
            },

            /** @return void */
            resetFields: function()
            {
                var fields = this.el[this.current].querySelectorAll( this.selectors[this.current] );
                for( var i = 0; i < fields.length; ++i ) {
                    fields[i].parentNode.classList[
                        this.addRemove( fields[i].tagName === 'SELECT' && fields[i].value !== '' )
                    ]( this.prefixed( 'is-active' ));
                }
            },

            /** @return void */
            resetPlaceholder: function( el )
            {
                var dataPlaceholder = 'data-placeholder';
                var originalPlaceholder = el.getAttribute( dataPlaceholder );
                if( originalPlaceholder !== null ) {
                    el.removeAttribute( dataPlaceholder );
                    el.setAttribute( 'placeholder', originalPlaceholder );
                }
            },

            /** @return void */
            setLabel: function( labelEl, el )
            {
                labelEl.classList.add( this.prefixed( 'label' ));
                labelEl.textContent = this.getLabelText( labelEl, el );
                if( typeof this.config[this.current].customLabel === 'function' ) {
                    labelEl.textContent = this.config[this.current].customLabel.call( this, labelEl, el );
                }
            },

            /** @return void */
            setPlaceholder: function( labelEl, el )
            {
                var placeholderText = el.getAttribute( 'placeholder' );
                if( this.config[this.current].prioritize === 'label' || !placeholderText ) {
                    if( placeholderText ) {
                        el.setAttribute( 'data-placeholder', placeholderText );
                    }
                    placeholderText = this.getLabelText( labelEl, el );
                }
                if( typeof this.config[this.current].customPlaceholder === 'function' ) {
                    placeholderText = this.config[this.current].customPlaceholder.call( this, placeholderText, el, labelEl );
                }
                if( el.tagName === 'SELECT' ) {
                    this.setSelectPlaceholder( el, placeholderText );
                }
                else {
                    el.setAttribute( 'placeholder', placeholderText );
                }
            },

            /** @return void */
            setSelectPlaceholder: function( el, placeholderText )
            {
                var childEl = el.firstElementChild;
                if( childEl.hasAttribute( 'value' ) && childEl.value ) {
                    var selected = el.options[el.selectedIndex].defaultSelected !== true ? true : false;
                    el.insertBefore( new Option( placeholderText, '', selected, selected ), childEl );
                }
                else {
                    childEl.setAttribute( 'value', '' );
                }
                if( childEl.textContent === '' ) {
                    childEl.textContent = placeholderText;
                }
            },

            /** @return void */
            wrapLabel: function( labelEl, el )
            {
                var wrapper = this.createEl( 'div', {
                    class: this.prefixed( 'wrap' ) + ' ' + this.prefixed( 'wrap-' + el.tagName.toLowerCase() ),
                });
                if( el.value !== undefined && el.value.length ) {
                    wrapper.classList.add( this.prefixed( 'is-active' ));
                }
                if( el.getAttribute( 'required' ) !== null || el.classList.contains( this.config[this.current].requiredClass )) {
                    wrapper.classList.add( this.prefixed( 'is-required' ));
                }
                el.parentNode.insertBefore( wrapper, el );
                wrapper.appendChild( labelEl );
                wrapper.appendChild( el );
            },
        };

        window.FloatLabels = Plugin;

    })( window, document );

js/script.js

    var floatlabels;
    var toggleBtn = document.querySelector( '.fl-toggle' );
    var styles = document.getElementsByName( 'style' );

    var getStyle = function() {
        for( var i = 0; i < styles.length; ++i ) {
            if( styles[i].checked ) {
                return styles[i].value;
            }
        }
        return 0;
    };

    var changeStyle = function( form ) {
        form.className = form.className.replace( /fl-style-\d/g, 'fl-style-' + getStyle() );
    };

    toggleBtn.addEventListener( 'click', function() {
        if( document.querySelector( '.fl-form' )) {
            floatlabels.destroy();
        }
        else {
            floatlabels = new FloatLabels( '.form-1', {
                style: getStyle(),
            });
        }
    });

    [].forEach.call( styles, function( style ) {
        style.addEventListener( 'change', function( ev ) {
            changeStyle( ev.target.closest( 'form' ));
        });
    });

    toggleBtn.click();

I appreciate everyone's help. I decided to follow the 2nd response's instructions, and I then realized that I can removed the mentioned script portion starting with " document.querySelectorAll(...)) " while keeping the the following portion:

new FloatLabels('.form-1', {
  style: 1
});

By doing so, I will leave the CSS intact and simply use the script above and alternate between the styles 0, 1, and 2 for Default, Style 1, and Style 2, respectively.

Again, I appreciate everyone's help! You guys are AWESOME !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM