Dimentica
Dimentica

Reputation: 805

Append javascript function to div

I need to add the following code to the footer of my page, but I have to do it using javascript code.

Code I need to add:

  <script type="text/javascript">
    (function (d, w, c) {
        (w[c] = w[c] || []).push(function() {
            try {
                    w.yaCounter39519115 = new Ya.Metrika({
                    id:39519115,
                    clickmap:true,
                    trackLinks:true,
                    accurateTrackBounce:true
                });
            } catch(e) { }
        });

        var n = d.getElementsByTagName("script")[0],
            s = d.createElement("script"),
            f = function () { n.parentNode.insertBefore(s, n); };
        s.type = "text/javascript";
        s.async = true;
        s.src = "https://mc.yandex.ru/metrika/watch.js";

        if (w.opera == "[object Opera]") {
            d.addEventListener("DOMContentLoaded", f, false);
        } else { f(); }
    })(document, window, "yandex_metrika_callbacks");

What I tried to add:

 $('#footer').append('<script type="text/javascript">' + (function (d, w,.... + '</script>');

However, this does not work for me.

Upvotes: 0

Views: 777

Answers (1)

David R
David R

Reputation: 15639

Place your javascript in a separate .js file and then you need to use the document.createElement method to add/append your script to your footer block.

Try the below snippet.

var scriptSource = document.createElement('script');
var scriptURL = 'your_script_file_url_goes_here';
scriptSource.type = 'text/javascript';
scriptSource.src = scriptURL ;
$("#footer").append(scriptSource);

Hope this helps!.

Upvotes: 3

Related Questions