Controling height in jQuery UI Accordion with dynamic data - jquery-ui

I'm using an jQuery accordion control with knockout to dynamically add/remove items to the control based on some client-side activity. I've created a knockout binding like such:
ko.bindingHandlers.accordion = {
init: function (element, valueAccessor) {
var options = valueAccessor() || {};
setTimeout(function () {
$(element).accordion(options);
}, 0);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).accordion("destroy");
});
},
update: function (element, valueAccessor) {
var options = valueAccessor() || {};
$(element).accordion("destroy").accordion(options);
}
}
Now my problem is the sizing of the accordion... it always looks very compressed (vertically). I've tried setting the height of the DIV that contains the control, like this:
<div id="LearningPaths" data-bind="foreach: allLearningPaths, accordion: {}" style="height:500px; border:1px solid red;">
But the panels in the accordion don't change... they still aren't very "tall". Here's what it looks like: http://sdrv.ms/STA9Y6
I think there's a setting I can pass in when I use the .accordion(), but with my binding handler I'm not sure how to do that as I'm already passing in the 'options' object.
What I want is to have the content area of each panel to expand to the entire available side in the accordion control... ideas?

First i think your problem is someone related to SharePoint web parts. I created a accordion solution which is based on the summary link web part in SharePoint and can be found here: http://www.n8d.at/blog/turn-summary-link-web-part-into-an-accordion/
I wrote my own accordion to accomplish this, which also makes sure that if you like to edit the page the accordion script won't be loaded.
On the other hand i think your problem is more related to css and not to jquery. Do you use float style in your css? Then you need to make sure that you use the so called clear-fix.
This can be done in define the following style:
.panel:after{
clear: both;
}

Related

Jquery UI tooltip - multiple tooltips

I'm using jquery UI for my tooltips. I would like to have more than one on the same page and have them open and close on click. I found a solution for having them open on click:
http://jsfiddle.net/rjGeS/83/
(taken from this link -> jQueryUI tooltip Widget to show tooltip on Click)
What I need help with is having multiple tooltips on one page.
I tried altering the code slightly to make it work, but its just opening them all
$('#tooltip_1').click(function() {
var $this = $(this);
$(".tooltip").html(function() {
$('.ttip').css({
left: $this.position() + '20px',
top: $this.position() + '50px'
}).show()
}).fadeIn();
});
$('#tooltip_2').click(function() {
var $this = $(this);
$(".tooltip").html(function() {
$('.ttip').css({
left: $this.position() + '20px',
top: $this.position() + '50px'
}).show()
}).fadeIn();
});
The example code you've posted actually has nothing to do with jQueryUI Tooltips, I'll give a clean example instead.
You can use the open() and close() functions to show and hide tooltips programmatically. If you also need to stop the default tooltip functionality (as in, showing them on mouseover events) the easy way to do that is to use the disabled option.
Since you didn't specify if this should be click-once-show-all or not, here's a fiddle doing it for all: http://jsfiddle.net/wuL9M/ and here's a fiddle doing it individually: http://jsfiddle.net/qnYRy/
Note this line:
$(".tooltip").off("mouseleave focusout");
It disables the default closing behaviour while the tooltip is open.
If you want to partially preserve only some of the default tooltip functionality, you can use a custom flag (instead of the disabled option), or you can attach extra event handlers to tooltipopen and tooltipclose. It's all pretty well documented here.
ADD: You can use the content option to customise the tooltip with any (potentially non-static) data. eg: http://jsfiddle.net/qnYRy/1/ You can change it after initialisation with the option function:
$("#myTooltip").tooltip("option", "content", "My updated tooltip data");
$("#myTooltip").tooltip("option", "content", function() { return "My updated tooltip data"; });
For obvious reasons this would require you to set the content for each tooltip separately. Also note that it will ignore any html title attribute you may have.

Disable entire jqGrid

I have been looking for methods on how to disable a jqGrid and I found some:
Using BlockUI plugin: http://jquery.malsup.com/block/
Using jqGrid options: loadui and set it to 'block'
First option is a great solution (I have not tried yet) and it is clearer maybe but I want to avoid using plugins if I can whenever I can do it by setting object properties so I am trying the second option but it is not working for me, jqGrid continues enabled.
My jqgrid in my asp.net mvc 4 view:
<div id="jqGrid">
#Html.Partial("../Grids/_PartialGrid")
</div>
and _PartialGrid:
<table id="_compGrid" cellpadding="0" cellspacing="0">
</table>
<div id="_compPager" style="text-align: center;">
</div>
so in the view, in script section I perform below on document ready and depending on the status of a property in my model (I disable it if id>0, otherwise I enable it on page reload):
#section scripts
{
#Content.Script("/Grids/CompGrid.js", Url) // Content is a helper javascript loader (see end of this post)
}
<script type="text/javascript">
$(document).ready(function () {
showGrid();
var disableCompGrid = #Html.Raw(Json.Encode(Model.ItemCompViewModel));
setStatusCompGrid(disableCompGrid.id > 0);
}
</script>
CompGrid.js is:
function showGrid() {
$('#_compGrid').jqGrid({
caption: paramFromView.Caption,
colNames: ....
}
function setStatusCompGrid(disabled) {
$('#_compGrid').jqGrid({
loadui: 'block',
loadtext: 'Processing...'
});
}
In the code above, also I have tried to pass as parameter disabled to showGrid function and depending on if it is true or false to set a variable to 'block' or 'enable' respectively and then setting loadui property with this variable but it is not working.
Content.cshtml:
#using System.Web.Mvc;
#helper Script(string scriptName, UrlHelper url)
{
<script src="#url.Content(string.Format("~/Scripts/{0}", scriptName))" type="text/javascript"></script>
}
Any ideas?
It's important to understand that the call $('#_compGrid').jqGrid({...}); converts initial empty <table id="_compGrid"></table> element to relatively complex structure of dives and tables. So you can do such call only once. Such call creates and initialize the grid. In other words the function showGrid has bad name. The function can be called only once. The second call of it will test that the grid already exist and it will do nothing. If you need to change some parameters of existing grid you can use setGridParam method.
In the case you can use absolutely another solution to block the grid. After the call $('#_compGrid').jqGrid({...}); the DOM element of the initial table get some expandos - new property or method. For example $('#_compGrid')[0] will contains grid property which contains beginReq and endReq methods. So you can first create the grid (in the showGrid function) and include options loadui: 'block' and loadtext: 'Processing...' in the list of options which you use. Then if you need to block the grid later you can use
$('#_compGrid')[0].grid.beginReq();
and the code
$('#_compGrid')[0].grid.endReq();
to remove blocking. See the demo which demonstrates this. Alternatively you can show overlays created by jqGrid manually like I described in the answer. The code will be simple enough:
var gridId = "_compGrid"; // id of the grid
...
$("#lui_" + gridId).show();
$("#load_" + gridId).text("Processing...").show();
to show the overlay and
$("#lui_" + gridId).hide();
$("#load_" + gridId).hide();
to hide the overlay. See another demo which works exactly like the first one.
you don't need any plugin. Just add/remove css:
.disabled {
pointer-events: none;
//optional
opacity: 0.4;
}
DEMO

jQuery UI in Backbone View adds elements, but doesn't respond to events

I'm building an app in which I'm using Django on the backend and jQuery UI/Backbone to build the front. I'm pulling a Django-generated form into a page with jQuery.get() inside of a Backbone View. That part works fine, but now I want to add some jQuery UI stuff to the form (e.g. a datepicker, some buttons that open dialogs, etc). So, here's the relevant code:
var InstructionForm = Backbone.View.extend({
render: function() {
var that = this;
$.get(
'/tlstats/instruction/new/',
function(data) {
var elements = $(data);
$('#id_date', elements).datepicker();
that.$el.html(elements.html());
}
};
return this;
}
});
The path /tlstats/instruction/new/ returns an HTML fragment with the form Django has generated. What's happening is that input#id_date is getting the hasDatePicker class added and the datepicker div is appended to my <body> element (both as expected), but when I click on input#id_date, nothing happens. No datepicker widget appears, no errors in the console. Why might this be happening?
Also, somewhat off-topic, but in trying to figure this problem out on my own, I've come across several code examples where people are doing stuff like:
$(function() {
$('#dialog').dialog(...);
...
});
Then later:
var MyView = Backbone.View.extend({
initialize(): function() {
this.el = $('#dialog');
}
});
Isn't this defeating the purpose of Backbone, having all that jQuery UI code completely outside any Backbone structure? Or do I misunderstand the role of Backbone?
Thanks.
I think your problem is right here:
$('#id_date', elements).datepicker();
that.$el.html(elements.html());
First you bind the datepicker with .datepicker() and then you throw it all away by converting your elements to an HTML string:
that.$el.html(elements.html());
and you put that string into $el. When you say e.html(), you're taking a wrapped DOM object with event bindings and everything else and turning into a simple piece of HTML in a string, that process throws away everything (such as event bindings) that isn't simple HTML.
Either give .html() the jQuery object itself:
$('#id_date', elements).datepicker();
that.$el.html(elements);
or bind the datepicker after adding the HTML:
that.$el.html(elements);
that.$('#id_date').datepicker();

Combining multiple JQuery UI statements to set up Button controls

I'm pretty new to JQuery and JQuery-UI, but I'm having fun with it so far. My Javascript skills are a bit rusty, however, so some things are giving me a bit of a headache.
I'm using Jquery UI to theme my site, and I have several buttons that I want to set up with the appropriate theme. Each button has a different icon, so I ended up with a bunch of statements that look like this:
<script type="text/javascript">
$(function() {
$('[id$="butFind"]').button({
icons: {
primary: 'ui-icon-search'
}
});
});
$(function() {
$('[id$="butUpdate"]').button({
icons: {
primary: 'ui-icon-disk'
}
});
});
$(function() {
$('[id$="butCancel"]').button({
icons: {
primary: 'ui-icon-cancel'
}
});
});
// and so on for several more controls
</script>
I'm using the [id$=] ("ID ends with") selector as the controls that I'm theming are ASP.NET LinkButtons on a Content Page based off of a Master Page, and they get renamed when rendered to something like "ctl00_ContentPlaceHolder1_butFindSku". The ASP.NET markup for the buttons is pretty simple, and looks like:
<asp:LinkButton ID="butUpdate" runat="server" Text="Update"
CommandName="Update" />
<asp:LinkButton ID="butCancel" runat="server" Text="Cancel"
CommandName="Cancel" />
The multiple functions to theme the buttons and designate the appropriate icons seems rather awkward to me. I keep thinking that I should be able to either loop through some defined array of controls and icons, or tackle it in some other way that would make it easier for me in the future, particularly when I'm adding other controls to the page.
Suggestions on better ways to set this up are appreciated! Thanks!
I would have suggested to associate the icons with the buttons using HTML5 data- attributes, but since you're using ASP.NET web controls it will be more complicated than it's worth.
You can, however, store the id suffixes and their respective icons in an object literal, and use $.each() to iterate over it:
$.each({
butFind: "search",
butUpdate: "disk",
butCancel: "cancel"
}, function(suffix, icon) {
$("[id$='" + suffix + "']").button({
icons: {
primary: "ui-icon-" + icon
}
});
});

Creating a jQuery UI sortable in an iframe

On a page I have an iframe. In this iframe is a collection of items that I need to be sortable. All of the Javascript is being run on the parent page. I can access the list in the iframe document and create the sortable by using context:
var ifrDoc = $( '#iframe' ).contents();
$( '.sortable', ifrDoc ).sortable( { cursor: 'move' } );
However, when trying to actually sort the items, I'm getting some aberrant behavior. As soon as an item is clicked on, the target of the script changes to the outer document. If you move the mouse off of the iframe, you can move the item around and drop it back by clicking, but you can not interact with it within the iframe.
Example: http://robertadamray.com/sortable-test.html
So, is there a way to achieve what I want to do - preferably without having to go hacking around in jQuery UI code?
Dynamically add jQuery and jQuery UI to the iframe (demo):
$('iframe')
.load(function() {
var win = this.contentWindow,
doc = win.document,
body = doc.body,
jQueryLoaded = false,
jQuery;
function loadJQueryUI() {
body.removeChild(jQuery);
jQuery = null;
win.jQuery.ajax({
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
dataType: 'script',
cache: true,
success: function () {
win.jQuery('.sortable').sortable({ cursor: 'move' });
}
});
}
jQuery = doc.createElement('script');
// based on https://gist.github.com/getify/603980
jQuery.onload = jQuery.onreadystatechange = function () {
if ((jQuery.readyState && jQuery.readyState !== 'complete' && jQuery.readyState !== 'loaded') || jQueryLoaded) {
return false;
}
jQuery.onload = jQuery.onreadystatechange = null;
jQueryLoaded = true;
loadJQueryUI();
};
jQuery.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
body.appendChild(jQuery);
})
.prop('src', 'iframe-test.html');
​
Update: Andrew Ingram is correct that jQuery UI holds and uses references to window and document for the page to which jQuery UI was loaded. By loading jQuery / jQuery UI into the iframe, it has the correct references (for the iframe, rather than the outer document) and works as expected.
Update 2: The original code snippet had a subtle issue: the execution order of dynamic script tags isn't guaranteed. I've updated it so that jQuery UI is loaded after jQuery is ready.
I also incorporated getify's code to load LABjs dynamically, so that no polling is necessary.
Having played with their javascript a bit, Campaign Monitor solves this by basically having a custom version of jQuery UI. They've modified ui.mouse and ui.sortable to replace references to document and window with code that gets the document and window for the element in question. document becomes this.element[0].ownerDocument
and they have a custom jQuery function called window() which lets them replace window with this.element.window() or similar.
I don't know why your code isn't working. Looks like it should be.
That said, here are two alternative ways to implement this feature:
If you can modify the iframe
Move your JavaScript from the parent document into iframe-test.html. This may be the cleanest way because it couples the JavaScript with the elements its actually executing on.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe/sortable-test.html
If you only control the parent document
Use the jQuery .load() method to fetch the content instead of an HTML iframe.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe2/sortable-test.html
Instead of loading jQuery and jQueryUI inside the iFrame and evaluating jQueryUI interactions both in parent and child - you can simply bubble the mouse events to the parent's document:
var ifrDoc = $( '#iframe' ).contents();
$('.sortable', ifrDoc).on('mousemove mouseup', function (event) {
$(parent.document).trigger(event);
});
This way you can evaluate all your Javascript on the parent's document context.

Resources