Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding icons to pseudo elements

I'm trying to add icons to my navigation (which dynamically changes) via JavaScript.

Here is my code (or JSFiddle):

var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
  content: attr(data-icon);
}
<div id="icon" data-icon="">
  Icon
</div>

But it is not working, why? When tried to edit data-icon attribute manually, icon appears. Otherwise just unicode of icon.

like image 774
venkatraj Avatar asked Jun 26 '17 07:06

venkatraj


People also ask

How do I add an icon to a code?

To insert an icon, add the name of the icon class to any inline HTML element. The <i> and <span> elements are widely used to add icons. All the icons in the icon libraries below, are scalable vector icons that can be customized with CSS (size, color, shadow, etc.)

Can I add icons to Font Awesome?

You can upload your own SVGs, add them to the library, then create a custom font combining FontAwesome with your own icons.


1 Answers

HTML entities don't have any meaning in CSS. If you want to follow that path you need to decode it first:

var icon = document.querySelector('#icon');
var tmp = document.createElement("span");
tmp.innerHTML = '&#x86;';
icon.setAttribute('data-icon', tmp.innerText);
#icon:after {
  content: attr(data-icon);
}
<div id="icon" data-icon="">
  Icon
</div>

... or, alternatively, just type character as-is (as long as your application is written in UTF-8):

var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
  content: attr(data-icon);
}
<div id="icon" data-icon="">
  Icon
</div>

Last but not least, CSS also accepts escape sequences but you need to use the appropriate syntax. This approach, however, does not seem to work for your specific character:

var icon = document.querySelector('#icon');
// Brackets added for visibility, not part of the syntax
icon.setAttribute('data-icon', '(\u0086)(\u2020)');
#icon:after {
  content: attr(data-icon);
}
<div id="icon" data-icon="">
  Icon
</div>

I presume it's related to the fact that U+2020 'DAGGER' (that works fine) is a regular character but the one you're using U+0086 'START OF SELECTED AREA' (which doesn't show) is a control character. As you mention in a follow-up comment, you're using FontAwesome and such libraries provide custom fonts that map certain code points to display icons (though they normally use private areas to avoid conflicts).

like image 170
Álvaro González Avatar answered Oct 24 '22 10:10

Álvaro González