Search code examples
javascriptjquerycoloris

How clearing coloris elements also to clear rectangle element of current color?


Using latest version of coloris( https://coloris.js.org/ ) in php8 / bootstrap 5.1.3 / jquery 3.6.1 app I have several coloris elements on my form defined as

        <input type="text" id="accent_color" name="accent_color"
            class="form-control"
            value="{{ $accentColor }}" data-coloris>

and I have a js function clearing these coloris elements with code :

        jQuery('#accent_color').val('');

It works, but at right side of the there is a rectangle element (like green block at examples page at https://coloris.js.org/examples.html) with current color - it is not cleared with this code.

How can I clear this rectangle element ?


Solution

  • https://github.com/mdbassit/Coloris#manually-updating-the-thumbnail

    The color thumbnail is updated when an input event is triggered on the adjacent input field. If you programmatically update the value of the input field, you may need to trigger the event manually using the following code:

    document.querySelector('#color-field').dispatchEvent(new Event('input', { bubbles: true }));

    So in short, if you are using javascript to change the value of the input element, you should also dispatch the input event to update the preview of the latest picked color:

    const colorpicker = document.querySelector('[data-coloris]');
    colorpicker.value = '';
    colorpicker.dispatchEvent(new Event('input', { bubbles: true }));
    

    In my example above I used vanilla javascript to fetch the intended element.. while if you need to use your same strategy (jQuery), just replace the first line with:

    const colorpicker = $('#accent_color')[0];
    

    //init the color picker
    Coloris({ el: '#accent_color' });
    
    $('#clear')[0].addEventListener('click', () => {
      const colorPicker = $('#accent_color')[0];
      colorPicker.value = '';  
      colorPicker.dispatchEvent(new Event('input', { bubbles: true }));
    });
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.css"/>
    <script src="https://cdn.jsdelivr.net/gh/mdbassit/Coloris@latest/dist/coloris.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <input id="accent_color" type="text" data-coloris>
    
    <button id="clear" style="cursor: pointer;">CLEAR VALUE!</button>