Add page-specific javascript or CSS in Joomla - javascript

How do you include a javascript or CSS file only on a certain article in Joomla?
I have one article which requires the jQuery UI and associated theme. Since this isn't being used on any other pages, I only want it for this particular article. Adding in the necessary <script> and <link rel="stylesheet"> tags in the HTML of the article doesn't work, since they get stripped out when saved.
If there was a method to include certain files, or to stop the stripping of those tags, that'd be really good.

I ended up creating a plugin to do this for a site I maintain; I may release the code for it, but it's pretty simple to explain. You build a content plugin that searches for tags like {css path/to/a/css/file.css}, strips them out, then adds the files to the HTML <head>. Once you have the name of the CSS or JS file you want to include, here is the code you use to get it in the header:
$document =& JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'path/to/style.css');
$document->addScript(JURI::base() . 'path/to/script.js');

For this job use the Joomla plugin "Sourcerer". You can put PHP and Javascript in articles with it and still have time left to bake a pie!
I just added the code to the article and it worked like a charm. Beware of evil editors that will strip parts of the code. Html Entities are your friend - you can use them.
Sample code:
{source}<?php
$doc =& JFactory::getDocument();
$doc->addStyleSheet( JURI::root( true ).'/example.css' );
$doc->addCustomTag( '<script src="/example.js" type="text/javascript"></script>' );
$doc->addScript( JURI::root( true ).'/example.js' );
?>{/source}

Set your editor to Editor - None, and use any <script> and <style> that you want.
Don't forget that you should avoid editing that article using TinyMCE or other editors later.

Related

How would I dynamically clone a site and apply custom css to it?

So my school has a "portal"; a site with heaps of resources for the students and teachers. Only downside is that it is really, really badly designed and runs on HTML4. I have some decent web design skills and I want to try and improve it. I have asked if I could directly edit it and I was very quickly shut down. So how would I go about cloning the site while applying custom CSS?
While doing an iframe seems like a great idea to start with, it is quickly stopped by CORS. You can't apply custom CSS to an iframe with an origin of a different domain.
I could just download the site's source code and write custom CSS for that, but that way it won't update when new content is updated.
I am happy to play around with django/flask if needed since I have a lot of experience with python and if it works, I can create a downloadable app using react or something.
Anyone got any ideas?
Just go to the website you want to clone
Right click
Inspect element
Copy the whole html code
Paste it to you code editor
Add a tag a <style>
Enter Css to customize it with respect to the tags of the html code
You are done!!!
Happy coding :)
If I wanted to clone someone else's terribly built website, I would use PHP and DOM parsing.
https://codingreflections.com/php-parse-html/
In a perfect world, their code will follow some kind of pattern and, using the DOM parser, you'd be able to pick out their navigation and internal href links, and rewrite them to point to your site like http://terriblewebsite.com/aboutus.phtml => http://imborrowingyourwebsite.com?page=http://terriblewebsite.com/aboutus.phtml.
I would write all my css in a single file, remove their <link tags and insert my own css file links -- but use their classes as much as possible.
Your index.php file would basically be (this is a rough sketch)
<?php
$url = "http://terriblewebsite.com";
if ($_GET['url']) $url = urldecode($_GET['url']);
$dom = new DomDocument();
# $dom->loadHTML($url);
// change nav
$nav = $dom->getElementById('navbar'); //DOMElement
$nav_links = $nav->getElementsByTagName('a'); //DOMNodeList
foreach($nav_links as $item) {
$item->setAttribute('href', 'http://imborrowingyourwebsite.com?page='.$item->getAttribute('href'));
}
// ... other transformations...
// finally
echo $dom->saveHTML();
?>

Correctly syntax-highlighting javascript in phpstorm

In an existing laravel application I'm working on, .blade.php files contain a body section with my html and php in it. After the body section they contain a custom_js section which is used for inserting javascript code. In the parent template, the custom_js section is embedded like this:
<script>
#include('custom_js')
</script>
I can't get correct syntax highlighting in my .blade.php files for my javascript code. Php and html is highlighted correctly.
If I put the javascript code inside <script> tags the highlighting works fine and that's how the other developers have worked so far but before deployment you will have to remove these tags or else there would be 2 opening and 2 closing <script> tags. I don't feel comfortable with changing the parent template because that would cause enourmous refactoring effort.
I've already tried setting the Template Data Language of this specific file to various languages but that didn't help.
Is there an easy way or do I have to stick with inserting and removing <script> tags manually before deploying?
I'm using PhpStorm 8.0.3.
The best solution would be
...is to use comment-style language hinting - something like
// #lang JavaScript
someCode();
// #endlang
Something similar is described with language injecting, but I was not able to make this work in this manner :/ - I will update this if I do, I've started a separate question on the generic matter here: How to set syntax highlighting to a code section to a specific language programatically/with comments?
Less prettier way
...is to use Language injections directly - right click the code and click Show context actions (or Alt+Enter) => select Inject language or reference => select language of your choosing, although this does highlight the JavaScript, for me it damages the rest of the file's highlighting partially.
Ugly, but generic working solution
...is to trick PHPStorm in a way it thinks you are actually adding a <script> tag, but in fact you will comment it out.
{!! /* JS syntax highlighter !!}<script>{!! */'' !!}
var following = "javascript";
var doer = () => {
console.log(following);
};
The trick is based of fact that {!! X !!} is actually converted to just <?php echo X; ?> - normally it's a tool for displaying text you don't want to be HTML-escaped.
So the code than becomes
<?php echo /* JS syntax highlighter; ?><script><?php echo */''; ?>
And in the end it just "echos" the empty string.
You need to yield custom_js in the parent blade view.
Like so: #yield('custom_js')
No need to wrap it in script tags.
Wow. I'm really surprised phpstorm can't do the highlighting for you automatically -- in fact, I can't even find an option to force the syntax highlighting which is hugely disappointing since notepad++ can do it with 2 clicks.
My "solution" (it's ugly so I can hardly call it a solution) was to do this:
<script>
...some javascript...
</script>
#include("customJavascript")
<script>
...some javascript...
</script>
and then have open and close script tags in every included blade.php containing javascript fragments. This is really messy though, so I hope someone has a better solution for making code orderly.
If it is still actual:
Just put the tags into your custom_js file and put your code inside. PhpStorm will highlight everything correctly then.

Zend 1.11. headScript()->captureStart() content should be included last

we are working on a Zend 1.11. based application.
In the overall layout, we use
$this->inlineScript()->appendFile(...)
to add all required global libraries such as jQuery.
In some individual views, we need local JavaScripts we included via
<?php $this->inlineScript()->captureStart(); ?>
jQuery(document).ready((function() {
alert('ping');
}));
<?php $this->inlineScript()->captureEnd(); ?>
Here the problem is: The layout file is processed after the view, thus the captured content is obove the library include in the inlineScript stack. As a result, in the html, we get them printed in a way that jQuery is not loaded before our view specific script:
<script type="text/javascript">
//<!--
jQuery(document).ready((function() {
alert('ping');
}));
//-->
</script>
<script type="text/javascript" src="http://.../js/jquery/jquery-1.11.2.min.js"></script>
We did not found any solution browsing the Zend code to let the HeadScript helper print the includes first and the inline script afterwards. Does anybody know how to get this working (first including the script references and printing inline scripts afterwards)?
Thanks a lot
Ben
Aha, I should have checked the first code sample a bit more closely. In your layout you have:
$this->inlineScript()->appendFile(...)
you then said you wanted a solution to "let the HeadScript helper print the includes first and the inline script afterwards". But you aren't using the head script helper at the moment (at least none of the code in your question is).
The call in your layout should be:
$this->headScript()->appendFile(...)
and you will need a corresponding call to echo the result of the head script helper (within the <head>...</head> part of your layout). There are several examples in the documentation if you need to see how this should look.
Then you can leave the rest of your inline script calls as-is, and it shoudl all work fine.
I know the question is very old, but since i did not find any answer here or elswhere, i wanted to share my solution to the problem, it may maybe help someone else having the exact same problem.
Was looking for a answer myself
We are using ZendX_JQuery View Helpers (ZendX_JQuery_View_Helper_JQuery) to include jquery ($this->jQuery() on layout)
it has some nice functions to add JS-Files, but also scripts to the HEAD after the jquery was included, no mather if calling those after or before che inclusion of the jquery js-file itself.
Resolution of your specific problem would be:
<?php
$this->jQuery()->javascriptCaptureStart();
echo <<<JS
$(document).ready(function() {
alert('ping');
});
JS;
$this->jQuery()->javascriptCaptureEnd();

JQuery best practices

Ok guys, three questions here. They are all pretty noobish, but I just want to get your guys' thoughts on them.
1) When writing a jquery script, should I include type?
IE:
<script type="text/javascript" charset="utf-8">
//Jquery here
</script>
or is just an opening and closing script tag acceptable?
2) I know it's a best practice to include all JQuery just before the closing body tag, but does this also mean I include the actual jquery.js file just before body as well?
3) What if my page is reliant on jquery to look how it should (not just action events/ajax/etc). For example, I'm using a jquery plugin called datatables, which sorts through my specified database and automatically paginates/sorts/etc. I find that because I include all the scripts after the DOM loads, I see a raw format of the datatable until my datatables.js file and corresponding constructor loads. Would it be acceptable to include this before my body loads, so that this doesn't happen?
Including the type(type="text/javascript") is the best practice, though in HTML5 it's not needed as it's the default. In HTML 4 it's mandatory, but all modern browsers will read the script content as javascript if not specify, but it's still invalid according to the spec. You can read more here: Which is better: <script type="text/javascript">...</script> or <script>...</script>
Putting the jQuery script in the head is a good option, but it's not mandatory, it just have to be above all other scripts using the jQuery library.
Regarding to the plugin, it's hard to tell without seeing your code, and knowing how the plugin works. You can try move all the scripts to the <head> and see if it helps you. (It might still have the same effect if the plugin waits for the DOM ready. )

Best approach for including bits of Javascript on individual pages in Sitefinity

Frequently, I just want to drop a bit of jQuery on an individual page. Given my early understanding of Sitefinity, I think...
I can't easily put JS in the <head>.
I could put JS in a Generic Content control, but then my JS is sitting inline in the <body>. Maybe I need to relax, but I don't usually like to put much JS in the <body>.
It feels like this kind of scenario is an afterthought. Is JS a 2nd-class citizen in Sitefinity?
JavaScript does not live in the head. Yahoo even says it is better for performance
I agree with epascarello you really shouldn't be putting your javascript in the head anyway.
And just in case you didn't know about this the jQuery framework is part of Sitefinity. The article also shows you how you can include external libraries in sitefinity from anywhere withing your project whether it be master page or user control.
Why not have the jQuery code in a separate .js file and use unobtrusive JavaScript? With jQuery you can separate behavior and markup so nicely that you should never have to include JavaScript in your head or body ever again.
Just use the standard onLoad function in jQuery and put all of your initialization code in there.
Try it, I think that you will like it! If you like using CSS for separation of presentation and markup, then jQuery can do the same thing with behavior and markup.
This is an old question, but one way you can do it now is:
Add a Javascript block (under Scripts & Styles), and then paste the URL to the jquery code:
http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js
Then add another Javascript block with your jquery, like:
$(document).ready(function() {
alert("hello");
});
Or you can also paste the URL to your js file.

Categories

Resources