1

Iam using fontawesome for the icons right now. I have created my own icons ( in svg ) and now i try to use it as fontawesome does.

Everything is working, my icons are in a json file in svg format and on page load js loads all the icons inside the svg to the appropirate tags. But this is happens only once, on page load. What if i have some dynamically added elements on the body? I need a listener to any append event to readd every icon to the DOM.

Can i do this? How does fontawesome does it?

Here is how i do it right now:

var icons = [];
$(document).ready(function () {
    getIcons();
});

function getIcons(){
    $.ajax({
        url:'/fileDown?param0=/icons.json',
        success: function (data){
            if(IsJsonString(data)){
                icons = JSON.parse(data);
                insertIcons();
            }
        }
    });
}


function insertIcons(){
    for (const icon of icons ) {
        if(icon.svg !== ""){
            $(`.hsh.${icon.iconClass}`).html(icon.svg);
        }
    }
}

What i'm thinking on:

$("body").on("changed appendedTo", function () {
    insertIcons();
});

Example html for a basic fontawesome icon:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/a26f6e4ee4.js" crossorigin="anonymous"></script> <!-- init font awesome here -->
    <title>Document</title>
</head>
<body>
    <i class="fa fa-user"></i> <!-- user is there -->

<script>
 $(document).ready(function () {
    // plane icon will be there even after 5sec.
    setTimeout(() => {
      $("body").append(" <i class='fa fa-plane'></i> ");
    }, 5000);
 });
</script>
</body>
</html>
Dr.Random
  • 430
  • 3
  • 16
  • Fontawesome has nothing to do with listeners. You need to utilise event delegation. – VLAZ Jul 01 '21 at 06:19
  • This is not a duplicate. The recommended question is not the same. – Dr.Random Jul 01 '21 at 06:20
  • VLAZ. Font awesome does something in the background because all my icons inside my dynamic elements are there, even if i init fontawesome at the beginning of page load. – Dr.Random Jul 01 '21 at 06:21
  • Fontawesome SVG does replace all the tags in a page with an svg code. So they do it somehow – Dr.Random Jul 01 '21 at 06:22

0 Answers0