Created
June 12, 2019 19:58
-
-
Save AThraen/6cbe66024b81f310351cc051c677e51b to your computer and use it in GitHub Desktop.
Contentful Color Picker Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html><head> | |
| <!-- Our dependencies --> | |
| <link rel="stylesheet" href="https://contentful.github.io/ui-extensions-sdk/cf-extension.css"> | |
| <script src="https://unpkg.com/contentful-ui-extensions-sdk@3"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script> | |
| </head> | |
| <body> | |
| <div class="cf-form-field"> | |
| <!-- Here goes the input field, that we manipulate through javascript --> | |
| <input type="text" class="cf-form-input jscolor" id="color"> | |
| <div class="cf-form-hint">Pick the background color </div> | |
| </div> | |
| <script> | |
| window.contentfulExtension.init(function(api) { | |
| //api is the object giving us access to the Contentful API. | |
| //First, let's adjust the height of the iframe we are in, so it fits with what we need. | |
| //We could call api.window.startAutoResizer() but in this case I prefer to set a specific height: | |
| api.window.updateHeight(200); | |
| //For debugging purposes we can also output the value of the current field: | |
| console.log(api.field.getValue()); | |
| //Let's get the input field from the DOM: | |
| var inputfield=document.getElementById('color'); | |
| //We should set up an event listener for when it changes, so we can send the new value to Contentful: | |
| inputfield.addEventListener('change',function() { | |
| api.field.setValue(inputfield.value); | |
| }); | |
| //Also, what if something or someone else changed this value while we were editing it? | |
| //Better listen for that as well: | |
| api.field.onValueChanged(function(value) { | |
| if (value !== inputfield.value) { | |
| inputfield.value=value; | |
| inputfield.style.backgroundColor = '#' + inputfield.value; //Set the background color | |
| } | |
| }); | |
| //Finally, as we are still initializing here, let's update the input field with the value | |
| if(api.field.getValue()!=undefined){ | |
| inputfield.value=api.field.getValue(); | |
| //And update the background color! | |
| inputfield.style.backgroundColor = '#' + inputfield.value; | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment