Search code examples
javascriptsvgcolor-picker

Get color from wpColorPicker (Iris) after mouseup, keyup or done


I want to change fill color of SVG shape after user finish dragging on ColorPicker (wpColorPicker or IrisColorPicker) because there're dozen of SVG Shapes and every shape has a lot of circles, paths etc...

So i tried to find an event like [done, or something like that] in AutomatticIris but i failed only [change] is available Iris docs but because i get SVG shape from server using AJAX it's impossible to do this job in change event.


Solution

  • A common solution for these kind of problems is to clear and start a timer (by setTimeout) each time the change event occurs. So the timer only fires if the change event will not be fired for a certain time (the interval you set by setTimeout).

    Here is a snippet that changes the color of the headline 1 second (1000 milliseconds) after the last change in the color picker:

    jQuery(document).ready(function($){
        console.log('ready');
        var color = null;
        var timer = null;
        var changed = function(){
            console.log("Changed");
            $("#headlinethatchanges").css( 'color', color);
        };
        $('#color-picker').iris({
            width: 400,
            hide: false,
            change: function(event, ui) {
                if (timer) clearTimeout(timer);
                timer = setTimeout(changed, 1000);
                color = ui.color.toString();
            }
        });
    });
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
        <script src="http://automattic.github.io/Iris/javascripts/iris.min.js"></script>
        <script src="http://automattic.github.io/Iris/javascripts/prism.js"></script>
    
    <h1 id="headlinethatchanges">Iris Test</h1>
    <input type="text" id="color-picker" value="#bada55" />