0

I'm trying to create a bookmarklet based on the jQuery Color Picker Plugin. If I include the JavaScript file in the header of the page (example), everything works fine, but if I append the script to the page from the bookmarklet, the color picker never gets initialized (example). I've simplified the js as much as I could for clarity.

Here's the bookmarklet code:

javascript:(function()%20{_my_script=document.createElement('script');_my_script.type='text/javascript';_my_script.src='http://forwardbeats.com/sandbox/colorpicker.js';document.getElementsByTagName('head')[0].appendChild(_my_script);})();

The script is being appended to the page just fine and seems to be running, but the picker never gets initialized. Any ideas on what might be going wrong?

NOTE: I would also usually test for jQuery, among other things, to begin with, but for this example I'm assuming it's already on the page.

EDIT: I have found and solved the problem. I'll post my answer below in hopes that I can help anyone who has a similar situation.

dpcasady
  • 1,826
  • 12
  • 30
  • Why do you have a `%20` in your bookmarklet? It'll cause a syntax error. – Aadit M Shah Apr 27 '12 at 18:57
  • Oh really? I didn't know that! In most bookmarklets I've seen the spaces are encoded as `%20`. – dpcasady Apr 27 '12 at 19:01
  • check the console to see if a script element was even appended so you can rule out that – Kerstomaat Apr 27 '12 at 19:09
  • Yeah, it's being appended. If I add an alert or console log message to the js file it get's called, so I know the script is being run. I just can't figure out why the color picker doesn't get initialized this way – dpcasady Apr 27 '12 at 19:13
  • You don't need a space, let alone a `%20`, after a `function()` token (before the opening curly brace). – Platinum Azure Apr 27 '12 at 19:27
  • Don't you need an element on the page for the script to hook up with? – epascarello Apr 27 '12 at 19:36
  • NITPICK: `colorPicker();` should not be called before it is defined, that is bad practice. – epascarello Apr 27 '12 at 19:50
  • Thanks epascarello, and to answer your question, yes. The script looks for the `.colorSelector` class and initializes that (or tries to). That class does exist on both example pages. – dpcasady Apr 27 '12 at 19:56

1 Answers1

0

The problem wasn't in the bookmarklet at all, but the js file that I was including. For some reason the code worked fine when it was included with the page, but not when it was appended by the bookmarklet.

I noticed that when using the bookmarklet, the script was trying to call the color picker initialize function before it was registered. All I had to do to fix the problem was change where I was calling colorPickerInit() from. Before, I was calling it after eye() which is responsible for calling the functions which are registered in colorPickerInit(). By moving colorPickerInit() within eye() everything is now working correctly!

dpcasady
  • 1,826
  • 12
  • 30