10

A safe way to add JavaScript resources via the frontend, is to use the {% includeJsFile %} Twig function in your template. The nice thing about the includeJsFile function is that it doesn't matter where in your template you call it; the file(s) added will always be output just above your </body> tag (or wherever else you put your {% getFootHtml() %} ...


8

The only JS library that ships with Craft (besides the Craft-specific Garnish) is jQuery. Of course, jQuery is a helpful JS library, but by no means a full-fledged framework. Fortunately, adding a separate JS library is painfully easy! How to CDN from a Twig template... {% includeJsFile '//full/path/to/cdn.js' %} How to CDN from PHP... craft()->...


7

So far the only solution I have found is to use a plugin, and Lewis Jenkins' LJ Cookies plugin does the trick nicely: {{ craft.lj_cookies.get( NAME ) }} It also allows you to set and delete cookies within templates.


7

You can create a simple plugin with an init() method like so: public function init() { craft()->log->removeRoute('WebLogRoute'); craft()->log->removeRoute('ProfileLogRoute'); } That will prevent the extra logging and profiling information to be output in the browser's console when devMode is enabled.


7

As of Craft 2.4.2688: It is now possible to access Craft.BaseElementSelectInput objects from their container elements, via .data('elementSelect'). On select element: $('#theElementSelectField').data('elementSelect').on('selectElements', function(e) { console.log(e); // Take a look // Do stuff here when elements are selected... }); On remove ...


7

Yes, you can do all the normal commerce actions via ajax. A basic recipe is this... HTML: <form method="POST" id="addToCartForm"> {{ getCsrfInput() }} <input type="hidden" name="action" value="commerce/cart/updateCart"> <input type="hidden" name="redirect" value="/cart"> <input type="hidden" ...


6

You can get the Element Select’s JS instance like so: $(document).ready(function() { var elementSelect = $('#your-container-id').data('elementSelect'); }); (Replace your-container-id with whatever ID you passed into the id param when calling forms.elementSelect or forms.elementSelectField.) Then you can attach a selection callback to that: ...


6

So I just went through my article step-by-step and I indeed missed adding the new content into $main. I think there may have been a versioning mistake in the article's code as I definitely tested it. Anyways, here's an updated loadPage function for you. Which I will be adding to the article tomorrow. I've added a few extra things to ensure that there's no ...


5

You can't pass a JS variable into a JS file (that doesn't quite make sense). What you can do is to create a JS variable, and make it accessible to the script you are including. So you'd include your JS file as you are already doing: {% includeJsFile 'path/to/file' %} And then you would create your variable, and in JavaScript pass that variable back into ...


5

I use this to force the task icon to show up immediately: Craft.cp.setRunningTaskInfo({ "id": "task ID", "level": "0", "description": "description", "status": "running", "progress": 0 }); Craft.cp.trackTaskProgress();


5

95% of the time you see a 400 Bad Request error, it's because it's a CSRF token validation error (or you're just missing the token all-together). Craft 3 has CSRF validation enabled by default. Here's how to pass the CSRF token to your JS in Craft 2: https://craftcms.com/support/csrf-protection#updating-your-javascript Here's the CSRF token changes in ...


4

You can't disable the debugging output using Twig/templates. However, Craft will only render the debug data if your document' Content-type header is either "text/html" or "application/xhtml+xml" (source). This means that if you're outputting JSON, you can set the template's Content-type to "application/json" (using Craft's header tag), preventing Craft ...


4

Twig (and all php) is processed server-side before javascript even gets initiated. And once the page renders in the browser there no way to interact directly with twig. The only two options that you have is to either 1) reload the page or 2) request a page segment via ajax. I would opt for the later in this case. To do this, you could either listen for an ...


4

Think you need: UrlHelper::getResourceUrl('path/to/file.ext') There is more info over at http://buildwithcraft.com/docs/plugins/resources Edit ok, scrap that answer, I didn't read the rest of the help page :) I think you are nearly there though. I'll have a test on my local machine and get back to you. Edit 2 I believe I'm running into the same ...


4

Looks like you're actually off-track in a couple of different ways... ElementCriteriaModel This code is going to return an ElementCriteriaModel: craft.tags.group('gameTags') Think of an ElementCriteriaModel as being a pending search query... The only reason you'd need one is to either adjust the query further or run the query to get results. Fortunately ...


4

In your first example, you are outputting an ElementCriteriaModel. That is a query for tags rather than the tags themselves. It doesn't output anything usable by JS You're almost doing the same in the second example, except that your reference to gameTags in the JS is just referencing itself rather than any Twig output. What you want to do is to query the ...


4

The cleanest way to do this would be to provide your own Javascript class that overrides Craft.BaseElementIndex, which stores the latest search value in localStorage: MyElementTypeIndex = Craft.BaseElementIndex.extend( { onAfterHtmlInit: function() { // Do we have a stored search value? if (this.instanceState.searchVal) { ...


4

I don't believe there is a way to minify javascript when it is output to the page. If there is it would make for increased load time. My suggestion is to use a preprocessor like Gulpjs or Gruntjs. The basic workflow is when you update your JS file/s the preprocessor can detect the change and concatenate and minify your files into a production file. You ...


4

You could write some PHP at the top of your general.php file that reads the JSON manifest in your public root directory, and add its keys/values to the config array. I wouldn't use environment variables here, personally – just add the manifest to the returned array in general.php: // In general.php: $assetsManifest = @json_decode(file_get_contents($...


4

When an entry is saved, an Entry saved. flash message is set and displayed by Craft. You could use the Control Panel JS plugin to write a script to detect this flash message and perform your desired action. The flash message is set in a div with an id="notifications". When there is no notification present, this div is empty. When there is a notification ...


4

No. Twig gets compiled into PHP and is run entirely on the server.


4

Turns out my code was pretty much working but there was another issue in there that was stopping the map marker updating. I've since resolved it. The original form is huge so here's a cut down snippet of the part that does the marker update in case anyone needs it. This cut-down version isn't tested but should be good. Incidentally, the "parent element ID" ...


3

There's also Swig. We've successfully been able to share JS templating with Craft templates, and it's worked pretty well. Not without it's caveats, though. Mostly coming from slight syntax differences and available filters.


3

There is no built in client side/JS templating available out of the box that I know of. You can always render Twig templates via Ajax by calling a plugin controller and returning a rendered HTML string, but that doesn't seem to fit your use case.


3

I'm not sure if there's an "official" way yet but I've looked through the source a little bit and I think the most Craft-like way I would do it, following plugin conventions, is to extend Garnish.Base with a new object that attaches the listener. (function($) { var PluginName_KeyCapture = Garnish.Base.extend({ init: function() ...


3

The "Craft" javascript global object can only be used in the backend, not on the frontend.


3

The most reliable way I've found to listen for the entry type switching would be to add an ajaxComplete listener to the document object, testing the call's URL for the switchEntryType action handle: $(document).ajaxComplete(myAjaxCompleteHandler); function myAjaxCompleteHandler( e, status, requestData ) { if ( requestData.url.indexOf( 'switchEntryType' ...


3

It looks like the only easy way to hook into that event is to listen for the resize event on the window object. On line 55, it is triggering resize(). Looking at the code, I am not seeing any other way to listen for these events. The Craft.EntryTypeSwitcher class is getting instantiated but not getting assigned to any variable in the DOM, so there is no way ...


3

If you are hosting on an Apache server, check your rewrite rules. The output provided appears to be appending a / to the end of the URL - which would most likely return a 404 error as it thinks the file is actually a directory. To be more specific, check for any rewrite rules that add a trailing slash to directories (or in general). That is most likely the ...


3

Craft checks if a form has changed using javascript in the cp.js file, see line 196. You could replicate this quite easily yourself though, here is a stripped down example: var initialFormValues = $('form[data-confirm-unload]').serialize(); function checkFormChanged() { if ($('form[data-confirm-unload]').serialize() != initialFormValues) { ...


Only top voted, non community-wiki answers of a minimum length are eligible