[Answered ]-Script not working outside html body tag

2👍

The elements you are trying to augment on the DOM may not be finished loading and therefore do not exists when the javascript runs. By keeping it at the bottom of the body the elements exist when the javascript runs. You can use something like

$( document ).ready(function() {
  var cbpHorizontalMenu = {};
});

more info here https://api.jquery.com/ready/

👤axrami

0👍

If you are going to include your script in the head of the page (so before the body tag) there will be no escaping the need to include jQuery as part of your project (for cross browser reliabilty purposes). I suggest you download it to be able to load it locally from your disk, otherwise, here is the online link for it, you can just add this to your head (just before your own script tag) :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

You now need to use jQuery to make sure your DOM has completely loaded before your script is executed, you do this by wrapping you whole script code inside the ready function :

$(document).ready(function () {
    var cbpHorizontalMenu = (function() {
        var b = $("#cbp-hrmenu > ul > li"),
            g = b.children("a"),
            c = $("body"),
            d = -1;

        function f() {
            g.on("click", a);
            b.on("click", function(h) {
                h.stopPropagation()
            })
        }

        function a(j) {
            if (d !== -1) {
                b.eq(d).removeClass("cbp-hropen")
            }
            var i = $(j.currentTarget).parent("li"),
                h = i.index();
            if (d === h) {
                i.removeClass("cbp-hropen");
                d = -1
            } else {
                i.addClass("cbp-hropen");
                d = h;
                c.off("click").on("click", e)
            }
            return false
        }

        function e(h) {
            b.eq(d).removeClass("cbp-hropen");
            d = -1
        }
        return {
            init: f
        }
    })();
});

Leave a comment