Superlight vanilla javascript plugin improving forms look and functionality

Overview

Superlight pure javascript form switch plugin by LCweb

Give a modern look to your applications and take advantage of javascript events and public functions.
Vanilla javascript. No dependencies. Everything in a single 7KB file, all inclusive!


Top features list:

  • sigle 7KB file, no dependencies, 100% ES6 javascript
  • minimal integration efforts in existing forms
  • public functions to manage each field status
  • hook through textual selector or DOM object (yes also jQuery ones)
  • complete events tracking
  • custom texts support
  • optional compact mode
  • optional custom active color (supporting gradients)

Tested on all mordern browsers (don't ask for old IE support please)
For live demos check: https://lcweb.it/lc-switch-javascript-plugin


Installation & Usage

  1. include lc_switch.min.js

  2. initialize plugin targeting one/multiple fields.
    NB: first parameter may be a textual selector or a DOM object (yes, also jQuery objects)

<script type="text/javascript">
lc_switch('input[type=checkbox], input[type=radio]');
</script>

Options

Available options with default values

<script type="text/javascript>
lc_switch('input[type=checkbox], input[type=radio]', {

    // (string) "checked" status label text
    on_txt      : 'ON',
    
    // (string) "not checked" status label text
    off_txt     : 'OFF',

    // (string) custom "on" color. Supports also gradients
    on_color    : false,

    // (bool) whether to enable compact mode
    compact_mode: false
});
</script>

Public Functions

Available public functions to be called on initialized inputs

<script type="text/javascript">
const inputs = document.querySelectorAll('input[type=checkbox], input[type=radio]');
lc_switch(inputs):


// checks the field
lcs_on(inputs);

// unchecks the field
lcs_off(inputs);

// toggles targeted field
lcs_toggle(inputs);


// disables the field
lcs_disable(inputs);

// enables the field
lcs_enable(inputs);


// refreshes plugin interface retrieving input attributes (useful while changing HTML attributes directly)
lcs_update(inputs);

// destroys plugin initialization showing HTML fields again
lcs_destroy(inputs);
</script>

Public Events

<script type="text/javascript">
document.querySelectorAll('input[type=checkbox], input[type=radio]').forEach(function(el) {

    // triggered each time input status changes (checked and disabled)
    el.addEventListener('lcs-statuschange', ...);
    
    
    // triggered each time input is checked
    el.addEventListener('lcs-on', ...);
    
    // triggered each time input is uncheked
    el.addEventListener('lcs-off', ...);
    
    
    // triggered each time input is enabled
    el.addEventListener('lcs-enabled', ...);
    
    // triggered each time input is disabled
    el.addEventListener('lcs-disabled', ...);

});
</script>

Copyright © Luca Montanari - LCweb

Comments
  • Unsafe assignment to innerHTML

    Unsafe assignment to innerHTML

    I use lc_switch.js and have to get rid of "Unsafe assignment to innerHTML" warning. So i changed this part of the code : https://github.com/LCweb-ita/LC-switch/blob/02a930ee1d82c69d9f1f44383eb8516447158b86/lc_switch.js#L165

                // labels structure
                const on_label 	= (options.on_txt) ? '<div class="lcs_label lcs_label_on">'+ options.on_txt +'</div>' : '',
                      off_label = (options.off_txt) ? '<div class="lcs_label lcs_label_off">'+ options.off_txt +'</div>' : '';
    
     
                // default states
                let classes = 'lcs_'+ el.getAttribute('type');
                    
                classes += (el.checked) ? ' lcs_on' : ' lcs_off'; 
                
                if(el.disabled) {
                    classes += ' lcs_disabled';
                } 
                
                
                // enabled and apply custom color?
                const custom_style = (options.on_color && el.checked) ? 'style="background: '+ options.on_color +';"' : '',
                      custom_on_col_attr = (options.on_color) ? 'data-on-color="'+ options.on_color +'"' : '';
                
    
                // wrap and append
                const wrapper = document.createElement('div');
                
                wrapper.classList.add('lcs_wrap');
                wrapper.innerHTML = 
                '<div class="lcs_switch '+ classes +'" '+ custom_on_col_attr +' '+ custom_style +'>' +
                    '<div class="lcs_cursor"></div>' +
                    on_label + off_label +
                '</div>';
    

    To not use variable assignment to innerHTML

            ```
            // wrap and append MOD Removed Unsafe assignment to innerHTML by Netquik (https://github.com/netquik)
            const wrapper = document.createElement('div');
            wrapper.classList.add('lcs_wrap');
    
            const wrapper_inner = document.createElement('div');
            wrapper_inner.classList.add("lcs_switch", 'lcs_'+ el.getAttribute('type'), (el.checked) ? 'lcs_on' : 'lcs_off');
            if (el.disabled) wrapper_inner.classList.add('lcs_disabled');
            if (options.on_color) {
                wrapper_inner.setAttribute("data-on-color", options.on_color);
            }
            if (options.on_color && el.checked) {
                wrapper_inner.setAttribute("style", 'background: '+ options.on_color +';');
            }
            const wrapper_inner2 = document.createElement('div');
            wrapper_inner2.classList.add("lcs_cursor");
            wrapper_inner.appendChild(wrapper_inner2);
            if (options.on_txt) {
                const l_on = document.createElement('div');
                l_on.classList.add("lcs_label", "lcs_label_on");
                l_on.textContent = options.on_txt
                wrapper_inner.appendChild(l_on);
            }
            if (options.off_txt) {
                const l_off = document.createElement('div');
                l_off.classList.add("lcs_label", "lcs_label_off");
                l_off.textContent = options.off_txt
                wrapper_inner.appendChild(l_off);
            }
            wrapper.appendChild(wrapper_inner);
    
    
    
    Not sure if it can be done better but here is working as expected.
    opened by netquik 3
  • classes on input element is removed on initialising

    classes on input element is removed on initialising

    The class 'test_class' on this 'input' element is getting ridden after calling the 'lc_switch() method'.

    It is not possible to do proper styling if this is the case. You guyz should copy the class as well to the toggle button.

    opened by ghost 3
  • Add class

    Add class

    This is in response to issue #5 - I had a similar request, but as this module is made available to me via a form generator, I was not able to access the elements in CSS without there being a class on the parent element, which the form generator does not allow me to do. This will allow you to specify a class for the lcs_switch DIV that you can then reference in CSS to make the size changes you need to override the existing fixed sizes.

    opened by thirdwheel 1
  • Method to enable or disable switch

    Method to enable or disable switch

    A disabled input initializes with an lcs_disabled class but if you want to programmatically enable it you need to remove the class and also remove the disabled attribute from the input.

    Adding .lcs_enable() and .lcs_disable() methods would wrap these two changes into one method.

    opened by barthamark 1
  • onclick event

    onclick event

    Sometimes there are differences between setting the state programmatically (eg on initialization) and setting the state on click. My application sets the initial state based on values from database but I need to change it based on parameters. The problem is that there is only one event so I can not distinguish between them. Any easy way to agregate an onclick event?

    opened by xgregg 1
  • Addon-reviewers security risk

    Addon-reviewers security risk

    Hi i use your lib in an browser extension i wrote. Mozilla AMO reviewers rejected the add-on for some reasons among which:

    This add-on is creating DOM nodes from HTML strings containing potentially unsanitized data, by assigning to innerHTML, jQuery.html, or through similar means. Aside from being inefficient, this is a major security risk. For more information, see https://developer.mozilla.org/en/XUL_School/DOM_Building_and_HTML_Insertion . Here are some examples that were discovered:

    • libs/lc_switch.js#111

    Is there a way to solve this? escaping html? Thanks

    opened by netquik 1
  • Typo on the homepage

    Typo on the homepage

    Hi - thanks for this great plugin! I forked it absent-mindedly because I thought the homepage for it was in the git repo and I was going to create a PR, but I realize it's not. You have a small typo in your docs.

    screen shot 2015-06-16 at 7 01 17 pm

    onsole.log should be console.log

    Thanks again!

    opened by snipe 1
  • Is it possible to theme only one checkbox on a page ?

    Is it possible to theme only one checkbox on a page ?

    Hi,

    I'd like to use your switches for a webpage of mine, but I can't make it work on only a specific checkbox and not all of them.

    If you have any clue, that would be a great help !

    Thank you.

    Sincerly

    opened by gtrdblt 1
  • Fix bug with [ ] in form names - escape special chars in selectors

    Fix bug with [ ] in form names - escape special chars in selectors

    Hi,

    We got crashes when you used [] in input names that was radios, for example something like this:

    <input type="radio" id="account_type_change_version_0" name="account_type_change[version]" required="required" value="4">
    

    That was because [] was used in the CSS selectors. This PR escapes all special chars with \ before, and works good for us.

    opened by johanwilfer 0
  • Make it work with inputs wrapped into their label

    Make it work with inputs wrapped into their label

    Hello,

    I use your excellent LCSwitch with different CSS frameworks (Bootstrap, Bulma, Foundation, Materialize, Tailwind & UIKit) in conjunction with my PHP Form Builder.

    Some frameworks are wrapping the checkbox/radio inputs into their label (label[for="inputname"]) The consequence is that when we switch on/off, the switch toggles twice consecutively: 1 time triggered by the switch click, the other triggered at the same time by the label click event, which toggles the checkbox/radio, which itself triggers the el.change event

    So if the switch was Off, it goes On then Off again.

    I just added preventDefault(); on the parent label, it solves the problem in all situations.

    opened by migliori 0
  • Public Event Listener for input type checkbox that is unchecked

    Public Event Listener for input type checkbox that is unchecked

    Js Code event listener for lcs_off : document.querySelectorAll('input[type=checkbox]').forEach(function(el) { // triggered each time input is uncheked el.addEventListener('lcs_off', function() { var styleElem = document.head.appendChild(document.createElement("style")); styleElem.innerHTML = '.lcs_cursor: after { content: "\00D7" }'; }); });

           Html code for lcs switch:
           `<form><input type="checkbox" class="status" checked name="sample" value="1" /></form>`
           
           Switch Initialization:
           `lc_switch('.status', {
                    // (string) "checked" status label text
                    on_txt: 'Active',
                    // (string) "not checked" status label text
                    off_txt: 'Inactive',
                });`
                
                But the event listener for lsc switch off is not initiated on unchecked event.
    
    opened by Veeni2021 0
  • Feature Request: make events bubbling or dispatch a bubbling change event on toggle

    Feature Request: make events bubbling or dispatch a bubbling change event on toggle

    That way code that listens on document does not need to be changed after converting a checkbox to a switch.

    jQuery example: $(document).on("change lcs-statuschange", 'input' ...

    does not trigger (except when clicking on the <label for="input_id">, because browser does that).

    opened by clst 4
Releases(v2.0.3)
Owner
Luca
Italian web developer speciailzed in wordpress, PHP and jQuery applications. Envato elite author and one of the most popular Codecanyon publishers
Luca
Solid Forms provides several form control objects useful for making working with forms easier.

Solid Forms Solid Forms provides several form control objects useful for making working with forms easier. Demos and examples below. # solidjs yarn ad

John 28 Jan 2, 2023
A JavaScript library improving inspection of objects

Pro Inspector A JavaScript utility improving inspection of objects on Node.js. Introduction Let's suppose that we have this declaration. class Person

Reiryoku Technologies 60 Dec 30, 2022
GraphErr is an open-source error handling library for GraphQL implementations in Deno. It's a lightweight solution that provides developers with descriptive error messages, reducing ambiguity and improving debugging.

GraphErr Descriptive GraphQL error handling for Deno/Oak servers. Features Provides additional context to GraphQL's native error messaging for faster

OSLabs Beta 35 Nov 1, 2022
Pagination Manager is an useful framework for improving the use of object pagination in APIs like Discord.

Pagination Manager Pagination Manager is an useful framework for improving the use of object pagination in APIs like Discord. Lightweight module, ES6

tnfAngel 4 Jul 26, 2022
Custom alert box using javaScript and css. This plugin will provide the functionality to customize the default JavaScript alert box.

customAlertBoxPlugin Custom Alert Box Plugin Using JavaScript and CSS Author: Suraj Aswal Must Include CSS Code/Default Custom Alert Box Class: /* mus

Suraj Aswal 17 Sep 10, 2022
📦 Alpine JS plugin to extend the functionality of the official $persist plugin

Alpine JS Persist Extended Alpine JS magic method $storage extends the official $persist plugin to help you work with local storage ?? Example ?? <div

Mark Mead 11 Dec 28, 2022
A jQuery plugin to submit forms with files via AJAX and to get a response with errors.

jquery-ajaxform A jQuery plugin to submit form with files via AJAX and to get a response with errors. Browsers without FormData uses iframe transport

gozoro 2 Mar 30, 2021
A jQuery plugin to make your form controls look how you want them to. Now with HTML-5 attributes!

(jQuery) Uniform A jQuery plugin to make your form controls look how you want them to. Now with HTML-5 attributes! Works well with jQuery 1.6+, but we

Audith Softworks 2.2k Jan 2, 2023
A JavaScript plugin that provides snapping functionality to a set of panels within your interface.

PanelSnap A JavaScript library that provides snapping functionality to a set of panels within your interface. Introduction PanelSnap is a framework ag

Guido Bouman 616 Dec 16, 2022
A simple Node.js package that helps you not to look up JavaScript promise syntax every time you use it.

A simple Node.js package that helps you not to look up JavaScript promise syntax every time you use it. Simple: Provides abstraction of the promise sy

Saad Irfan ⚡️ 9 Oct 8, 2022
Responsive Tabs is a jQuery plugin that provides responsive tab functionality.

Responsive Tabs is a jQuery plugin that provides responsive tab functionality. The tabs transform to an accordion when it reaches a CSS breakpoint. You can use this plugin as a solution for displaying tabs elegantly on desktop, tablet and mobile.

Jelle Kralt 537 Dec 8, 2022
A plugin for the Obsidian markdown note application, adding functionality to render markdown documents with multiple columns of text.

Multi-Column Markdown Take your boring markdown document and add some columns to it! With Multi Column Markdown rather than limiting your document lay

Cameron Robinson 91 Jan 2, 2023
Accordion Slider is a jQuery plugin that combines the functionality of a slider with that of an accordion.

Accordion Slider - jQuery slider plugin A responsive and touch-enabled jQuery accordion slider plugin that combines the functionality of a slider with

null 0 Dec 29, 2022
jQuery plugin that combines the functionality of a grid with that of an accordion.

Grid Accordion - jQuery plugin A responsive and touch-enabled jQuery grid accordion plugin that combines the functionality of a grid with that of an a

null 1 Dec 16, 2022
Simple Cropper is a jQuery plugin which gives you ability to add cropping functionality to your web application

Simple Cropper is a jQuery plugin which gives you ability to add cropping functionality to your web application. It uses html5 canvas to create cropped images and css3, so it only works on latest browsers.

null 1 Feb 15, 2022
Look up a city and get back weather forecast for searched city and top News headline related to that city and an interactive map which shows the location of that city.

WeatheredVibes Description As a user I want to look up a city to get the current weather and suggested current news articles based on the location sea

Sepideh Ayani 3 Mar 12, 2022
A JavaScript plugin for creating a tickerboard effect. Plugin for React or vanilla JS.

ticker-board A JavaScript plugin for creating a tickerboard effect. See the Ticker Board page for more info. Importing it There are basically two ways

Robin James Kerrison 6 Aug 11, 2022
Project Cider. A new look into listening and enjoying Apple Music in style and performance. 🚀

Links Wiki Request Feature Report Bug View The Releases Install Sources Compiling and Configuration For more information surrounding configuration, co

Cider Collective 5.8k Jan 5, 2023
This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js

This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js. But in most cases, I would recommend you to use something like Express in a production project for productivity purposes.

Eduardo Dantas 7 Jul 19, 2022