Pergunta

I am trying to put a jQuery color picker into my website. The color picker, by lindekleiv, isn't working. The code that I have is:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$('input#myColorPicker').colorPicker({
      format: 'hex',
      size: 100
});
</script>

The Full Code of the page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="stylesheet" type="text/css" href="../css/mainpage.css" media="screen" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans|Josefin+Slab:400,700,700italic,400italic' rel='stylesheet' type='text/css' />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="jquery.ui.colorPicker.min.js"></script>
<script>
$(function() { // Wait for page to load
    $('#myColorPicker').colorPicker({
        format: 'hex',
        size: 100
    });
});
</script>
</head>

<body>

<div id="head">
<h1><span>Welcome to CodeTowel&copy;.</span></h1>
<h1>The place to code, with help from Towel!</h1>
</div>

<p>Snippets are bits of code that you can download and put into your webpage. We have seperate snippets for the <code>&lt;code&gt;</code>, <code>&lt;pre&gt;</code>, and <code>&lt;kbd&gt;</code> elements.</p>
<p>Don't like the colors for the current website? Change 'em!</p>
<input id="myColorPicker" type="text" />
</body>
</html>
Foi útil?

Solução

Your code has a few problems that are stopping this from working... here they are:

  1. The plugin requires jQuery UI - you need to load that
  2. You are not loading the actual Javascript file that contains the plugin
  3. You are not loading the stylesheet file
  4. You need to wait for the page to load before using .colorPicker
  5. This is not that important, but I recommend changing your selector (input#myColorPicker) to something like #myColorPicker

So.. here would be the final code, after making all of these changes:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript"></script>
<script src="jquery.ui.colorPicker.min.js"></script>
<link rel="stylesheet" href="css/jquery.ui.colorPicker.css">
<script>
$(function() { // wait for page to load
    $("#myColorPicker").colorPicker({
        format: 'hex',
        size:   100
    });
});
</script>

Then where you want to put your color picker in your HTML, put

<input type="text" id="myColorPicker" name="color" />
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top