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.
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!