Drupal 6 - Add Javascript to a View - javascript

I want to add a Jquery plugin to a view. However, I don't want to add via the .info file, as I don't want it on every page. I also don't want to add it to the header of the view or create a view.tpl.php file.
This page shows how to add Java Script to a Node via template.php. Is there anyway to do something similar to add Java Script to a View via the template.php file?

Here is an example for Daniel Wehner's answer. It assumes your view is called 'blog', and your display id is 'page_1'. This code goes into template.php. Remember to clear the template cache after adding new functions to template.php.
/**
* Implements hook_preprocess_views_view().
*/
function THEMENAME_preprocess_views_view(&$vars) {
$view = $vars['view'];
// Load the blog.js javascript file when showing the Blog view's page display.
if ($view->name == 'blog' && $view->current_display == 'page_1') {
global $theme;
drupal_add_js(drupal_get_path('theme', $theme) . '/js/blog.js', 'theme', 'footer', FALSE, TRUE, FALSE);
}
}

You can use the hook hook_preprocess_views_view

Related

Trying to hide a view but I need help in trying to move the code to the asset library and only have a reference on the "page"

I am trying to customize the page for a view to not display a specific view (aka I would like to hide another view from a specific view's page). Ideally based on group membership. The eventual goal is to have all my code in my site assets to allow for re-use on other pages/views.
I have the code that will remove the view and if I place it in the Script Editor, it works. Since I am trying to put all my code in my site assets, once I move it to the sites assets library and then I add my reference, the code no longer runs.
My code in the Site Assets is the following: (this same code surrounded by tags functions when on the page and in a script editor.
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function () {
function init() {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
Templates: {
Header: function (ctx, columns) {
var views = JSON.parse(ctx.ListSchema.ViewSelectorPivotMenuOptions);
//display all View options except 'Create View' & 'Modify View'
ClientPivotControl.prototype.SurfacedPivotCount = views.length;
views = views.filter(function (view) {
console.log(view.DisplayText, view);
var isMenu=view.MenuOptionType===2;
return isMenu || view.DisplayText.indexOf('Owner') <0; // false will not be returned
});
ctx.ListSchema.ViewSelectorPivotMenuOptions = JSON.stringify(views);//create string defintion again
return RenderHeaderTemplate(ctx, columns); //render default Header template
}
}
});
}
RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~siteCollection/Style Library/hideview.js"), init);
init();
});
My reference that I now add in my script editor to reference the above code from the site Assets library is:
<script type="text/javascript" src="../SiteAssets/js-test/HideOwnerViews.js"></script>
I would like the functionality of hiding the view with the code in the site assets library and not directly embedded in the page.
If your js library host in root web, reference the library as
<script type="text/javascript" src="/SiteAssets/js-test/HideOwnerViews.js"></script>
If your js library host in child web, reference the library as
<script type="text/javascript" src="/site/child/SiteAssets/js-test/HideOwnerViews.js"></script>

Disable JS Popup Script On Specific Page

[!Newbie alert!] I'm using a ecommerce platform that doesn't allow me to edit the source code. I can only add new codes (html, js or css) to try to do the modifications I want. And what I want to do is to find a way to disable the script of a newsletter popup on only one specific page. The only way I thought of doing it is adding an extra JS script limiting the action of the previous script that I am not allowed to edit. Is it possible to do?
The original script for de Newsletter Popup is this:
<script type="text/javascript">
$(function() {
iniciarModalNews();
});
function iniciarModalNews() {
if (!$.cookie('showModalNews')) {
showModalNews();
};
}
function showModalNews() {
$.fancybox.open({
type: 'html',
minWidth: 270,
maxWidth: 350,
content: $('#modalNewsletter'),
beforeClose: function() {
$.cookie('showModalNews', 'hide', {
expires: 1,
path: '/'
});
}
});
}
</script>
It runs on all pages of the website and I want to exclude just one page. Is there a way to do this?
Thanks
Full Disclosure: This suggestion would not be considered a best practice but if its a one-off scenario where you don't have access to the source code it'll work.
If you only need to disable this on one page and have access to insert a block of script below the declaration of showModalNews() { ... } you can override the showModalNews() function by writing a new function with the same name. The method that calls the showModalNews method is inside an closure via IIFE (https://developer.mozilla.org/en-US/docs/Glossary/IIFE) but the method showModalNews() is NOT wrapped in a closure which would give you access to override it.
Example of the overridden method
function showModalNews() { ; }

How to make CKEditor image responsive in rails

I m using gem 'ckeditor', github: 'galetahub/ckeditor' with rails admin.
I want when I post article on the homepage, images associated with article's description should be automatic responsive. I have one folder in
assets/Javascript/ckeditor
, and I posted this piece of code in this folder, but it seems not working too. please help me out. thanks in advance.
If you want inserted images in a CKEditor to be responsive you can use the following code. It creates a htmlfilter for the
image tag that replaces inline "width" and "style" definitions with
their corresponding attributes and add's (in this example) the
Bootstrap "img-responsive" class.
I believe CKEDITOR does not add the img-responsive class to those images. You can check this by adding an image with CKEDITOR and then check if the html on the page has the img-responsive class added.
The function CKEDITOR.on() the event 'instanceReady' will execute the code to add the 'img-responsive' class to the image element el
The fact is, I believe you should put a breakpoint inside that code and test if it is actually executing
CKEDITOR.on('instanceReady', function (ev) { // etc.. etc.. });
because this are the instruction on how to adapt ckeditor with turbolinks
Create a file app/assets/javascripts/init_ckeditor.coffee
var ready = function() {
CKEDITOR.on('instanceReady', function (ev) { // code });
}
$(document).ready(ready)
$(document).on('page:load', ready)
Make sure the file is loaded from your app/assets/javascripts/application.js
CKEDITOR is the API entry point. The entire CKEditor code runs under this object.
The documentation of the .on() jquery method can help you understand better why that call is not executing, basically the .on() method trigger the js code in the function(){}, when that event is triggered.
The event is instanceReady and this is the info from the API
instanceReady( evt )
Event fired when a CKEDITOR instance is created, fully initialized and ready for interaction.
Parameters
evt : CKEDITOR.eventInfo
editor : CKEDITOR.editor
The editor instance that has been created.
Method 1
Add this in your CSS file:
img {
max-width: 100%;
height: auto !important;
}
Method 2
Use Enhanced Image plugin to replace the default image widget.
Method 3
Use the snippet in your link, but remember to replace the img-responsvie to img-fluid if you use Bootstrap 4.

How to include .js files in own Typo3 6.2 Extension?

I made an extension in Typo3 6.2 with extension builder, extbase and fluid.
I want to add a timepicker in the frontend.
I found a .js file online and want to include it whenever the extension is active because I need it often.
I placed that file here: EXT:/Resources/Public/JS/timepicker.js.
I saw a solution in this article but adding
page.includeJS.tx_myExtension = EXT:/Resources/Public/JS/timepicker.js
at the bottom of my setup.txt isn't working.
I didn't define a page there anyway so I think this might be the reason but I really have no idea - this is my setup.txt (autogenerated) in /typo3conf/ext//Configuration/TypoScript/:
plugin.tx_myext_test {
view {
templateRootPath = {$plugin.tx_myext_test.view.templateRootPath}
partialRootPath = {$plugin.tx_myext_test.view.partialRootPath}
layoutRootPath = {$plugin.tx_myext_test.view.layoutRootPath}
}
persistence {
storagePid = {$plugin.tx_myext_test.persistence.storagePid}
}
}
Ultimately I want my frontend function to work which already works with datepicker because I included jQuery in my root template. But I don't want to include the timepicker in there, just for my extension.
<script>
$(function () {
$('.lc-datepicker').datepicker();
$('.lc-timepicker').timepicker();
});
</script>
You can either use the correct syntax for EXT: like this:
page.includeJS.myextension = EXT:extkey/Resources/Public/JS/timepicker.js
(You forgot extkey.)
Keep in mind that it may improve performance of your website to use includeJSFooter instead of includeJS.
page.includeJS is a TypoScript property that is globally available. So if you use this in the root TS template of your site, the JavaScript file will be embedded to every page, regardless of whether the plugin is in use or not. So I suggest to use the Fluid approach below if you want to have the JS only on pages that have the plugin embedded.
To achieve this, use the Resource ViewHelper in your template:
<script src="{f:uri.resource(path: 'JS/timepicker.js')}"></script>
<script>
$(function () {
$('.lc-datepicker').datepicker();
$('.lc-timepicker').timepicker();
});
</script>
The Resource ViewHelper uses a path relative to the Resources/Public directory of your extension.
You could define to include JS in your controller class, to ensure it only loads for your extension.
In TypoScript, to have JS file configurable:
plugin.tx_myext.settings.javascript.file = EXT:myext/Resources/Public/JS/timepicker.js
In Controller action:
$this->response->addAdditionalHeaderData('<script src="' .
$GLOBALS['TSFE']->tmpl->getFileName($this->settings['javascript']['file']) .
'" type="text/javascript"></script>');

Ruby on Rails: render javascript only in defined page with turbolinks enabled

I have javascript embedded to a view in Rails that uses Turbolinks, e.g:
ViewX.html.haml:
.blah
Blah
:javascript
$(function() {
$(".blah").offset().top;
});
Everything works fine when I load ViewX. But then when I navigate to View Y I get the following error in console:
Uncaught TypeError: Cannot read property 'top' of undefined
And that error persists as I navigate to other views. It goes away when doing a hard refresh, but returns next time I render ViewX.
My question is how do I have some JS snippets render only for a particular view and not pollute to the rest of the app?
EDIT
Ok, I figured out a way, which is somewhat of a hack, but a contained hack. Change ViewX.html.haml to:
ViewX.html.haml:
.blah
Blah
%script{:type => "text/javascript", 'data-turbolinks-eval' => 'false'}
:plain
$(function() {
$(".blah").offset().top;
});
A simple way is to have each view have a different css class on the body tag:
var bodyClass = $('body').attr('class');
switch(bodyClass) {
case 'home-page':
// do stuff
break;
case 'about-page':
// do stuff
break;
}
If there is a lot of code for each page, you can use the a module pattern and make each module a separate .js file.
case 'home-page'
MyModule.initialize(); // set up form validation or whatever you need
break;
Another option (if you can't add a CSS class to the body tag) is to use a hidden <input> tag that holds the name of the view and use that to switch.
var switchJS = $('input[type=hidden]').attr('data-view');
/* i.e. <input type="hidden" data-view="my-home-page" /> */
switch(switchJS) { ...

Categories

Resources