Reputation: 33
I have some inline Javascript in my <body>
that I'm trying to export to a .js file. I know that normally you would just copy/paste it over, sometimes including it in a document ready function, but something about this one is different. I'm not super fluent in JS and the code wasn't written by me (but was provided free online).
This is how the code is in my file. If you need any more info just ask!
<body>
<script>
(function (window, document) {
var menu = document.getElementById('menu')
, WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
function toggleHorizontal() {
[].forEach.call(document.getElementById('menu').querySelectorAll('.custom-can-transform'), function (el) {
el.classList.toggle('pure-menu-horizontal');
});
};
function toggleMenu() {
// set timeout so that the panel has a chance to roll up
// before the menu switches states
if (menu.classList.contains('open')) {
setTimeout(toggleHorizontal, 500);
}
else {
toggleHorizontal();
}
menu.classList.toggle('open');
document.getElementById('toggle').classList.toggle('x');
};
function closeMenu() {
if (menu.classList.contains('open')) {
toggleMenu();
}
}
document.getElementById('toggle').addEventListener('click', function (e) {
toggleMenu();
e.preventDefault();
});
window.addEventListener(WINDOW_CHANGE_EVENT, closeMenu);
})(this, this.document);
</script>
</body>
UPDATE:
I was able to wrap the script in a scope (foo = function() {}
) and get it to work externally by adding window.onload = function
to the HTML page. This was suggested by @marmeladze and worked.
Upvotes: 0
Views: 2424
Reputation: 33
As suggested by @marmeladze, I was able to wrap the script in a scope (foo = function() {}
) and get it to work externally by adding window.onload = function
to the HTML page.
Upvotes: 1
Reputation: 144
So what is the real problem to export it in an external js file?
As always i would copy and past code in a new js. Link it to HTML page and write functions that i need as attribute of HTML's tag (ex. "onload=functioname();" in body's tag). As marmeladze said you can wrap all in an unique scope so you can call it in body.
Maybe you are doing it so if you maybe can explain better your problem would be great.
Upvotes: 0