Magento ver. 2.0.18
I created a custom module in backend there is color picker options.
for this i used this link color picker answer of @EmizenTech
it works perfectly but some time it gives and if i refresh the page error gone, in network i can see the jquery is loaded before the colorpicker.js
index):421 Uncaught TypeError: $el.ColorPicker is not a function
at HTMLDocument.<anonymous> ((index):421)
at fire (jquery.js:3232)
at Object.add [as done] (jquery.js:3291)
at jQuery.fn.init.jQuery.fn.ready (jquery.js:3542)
at (index):416
at Object.execCb (require.js:1650)
at Module.check (require.js:866)
at Module.<anonymous> (require.js:1113)
at require.js:132
at require.js:1156
My /var/www/html/magentoce20/app/code/Companyname/ModuleName/Block/Color.php
<?php
namespace Companyname\ModuleName\Block;
class Color extends \Magento\Config\Block\System\Config\Form\Field {
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param Registry $coreRegistry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context, array $data = []
) {
parent::__construct($context, $data);
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) {
$html = $element->getElementHtml();
$value = $element->getData('value');
$html .= '<script type="text/javascript">
require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {
$(document).ready(function () {
var $el = $("#' . $element->getHtmlId() . '");
$el.css("backgroundColor", "'. $value .'");
// Attach the color picker
$el.ColorPicker({
color: "'. $value .'",
onChange: function (hsb, hex, rgb) {
$el.css("backgroundColor", "#" + hex).val("#" + hex);
}
});
});
});
</script>';
return $html;
}
}
My /var/www/html/magentoce20/app/code/Companyname/ModuleName/view/adminhtml/layout/adminhtml_system_config_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<head>
<css src="jquery/colorpicker/css/colorpicker.css"/>
</head>
</page>
My /var/www/html/magentoce20/app/code/Companyname/ModuleName/view/frontend/requirejs-config.js
var config = {
deps: [
"Companyname_ModuleName/js/main",
],
map: {
'*': {
'slickjs': 'Companyname_ModuleName/js/slick/slick'
}
}
};
UPDATE : I just wrapped my colorpicker
code in load so that html loads completely first and than js comes , i know require is doing same thing in magento 2 but currently this solves my issues.
$(window).load(function() {
adminhtml_system_config_edit.xml
i shared the code above – inrsaurabh Apr 4 '18 at 5:08