I created TinyMCE plugin for WordPress editor to insert Youtube videos. Everything works fine except this button has no hover state (like the default buttons have). I explored the code and found a difference – default buttons are spans with background-image sprite, and my custom button is a plain image. There’s no option in TinyMCE addButton()
function to insert a span, only image:
ed.addButton('p2_youtube_button', {
title : 'Insert Youtube video',
cmd : 'mceYoutube',
image: url + '/shortcode-youtube.png'
});
Is there a way to solve this little problem?
To illustrate how it looks (the red Youtube icon should be gray and turn red on hover):
I noticed that the Crayon Syntax Highlighter plugin has managed to do this. It is a bit of code to read through, I found the tinyMCE specific part in /wp-content/plugins/crayon-syntax-highlighter/util/tag-editor/crayon_tinymce.js . I hope this helps.
The style which causes the highlight is here:
The image uses the same size as the other TinyMCE icons:
There are additional parameters you can pass to the addButton method that give you some options for how you skin your button.
If you remove the
image
property and replace it withicon
, you can use a font-ified icon instead. This is a multi-step process, which starts with actually building your icon font. Here’s a good tutorial that walks you through the process. The tutorial author recommends IcoMoon as a reliable way to build your icon fonts. There are probably others.The way that I use is similar to @feonix83’s approach, using CSS instead. Following the way WordPress itself does it, you lay your icons out in a sprite sheet, with the “hover” state 20px above the “off” state. If you don’t know what I’m talking about, take a look at the defalt WordPress icon sprite sheet:
wp-includes/images/wpicons.png
If you remove the
image
property altogether, TinyMCE just puts a span of classmceIcon
inside the button anchor block. It’s quite easy then to style that element and use thebackground-image
referencing your sprite sheet. You usebackground-position
to set the offset for the appropriate icon.There’s one additional trick that you can use to help you target only your buttons. You can add a
class
property to theaddButton
call and pass any number of classes. You will need to manually specify a specific class that can be used to target that button in particular, but you can also pass in an additional class that can be used to style all your buttons at once, since they won’t automatically inherit the styles that WordPress uses.class: "my-buttons my-specific-button"
Here’s the CSS that I use. Note that this approach works best when each button has its own individual sprite sheet, as opposed to the WordPress approach that loads all the icons at once, though that approach has some performance benefits that are not to be ignored: