I'm working on adding a simple feature to a single Joomla article. Editing the article itself is necessary in this case, I can't modify the template files (or add the JS to the entire site).
In the article editor (as per the doc), my article is as follows ...
{source}
<?php
$doc = JFactory::getDocument();
$doc->addStyleSheet('mycode/css/article_1.css');
$doc->addScript('mycode/js/article_1.js');
?>
{/source}
<div id="article_1"></div>
When viewing the page, both CSS and JS are loaded, but addScript()
is first-come-first-served, so my script (which contains jQuery) loads before jQuery. The console spits out:
Uncaught TypeError: $ is not a function
I tried changing the addScript
line to ...
$doc->addCustomTag('<script src="mycode/js/article_1.js" defer></script>');
... (note the defer
tag) but that doesn't seem to do anything (the script isn't added). I saw somewhere that I could use ...
$doc->addScript('mycode/js/article_1.js', 'text/javascript" defer="false');
... but the editor (both TinyMCE and CodeMirror) encodes the " above (to & quot;) which breaks that possibility.
I've also tried wrapping the article_1.js
code in an event listener ...
document.addEventListener('DOMContentLoaded', function(){ ... }
... but that doesn't seem to help :\ I still get:
Uncaught TypeError: $ is not a function
How do you add a jQuery script from within an article?