CollapsiblePanelExtender: Can I initiate collapse/expand from client-side javascript? (AJAX Control Toolkit) - ajaxcontroltoolkit

The CollapsiblePanelExtender seems primarily designed to collapse/expand things in response to user mouse events. Is there also a good way to get the extender to collapse/expand things in response to client-side javascript?
In my particular case, I have a number of CollapsiblePanelExtenders (and their corresponding Panels) on a page, and I'm wondering if I could implement an "expand all panels" button by doing something like this strictly on the client side:
for each CollapsiblePanelExtender on this page, call somethingOrOther(extender)
I can implement this logic server-side instead if I did a full postback, but my page takes a long time to load, and so this doesn't seem like it would provide a very slick user experience. Thus I am interested in doing expand/collapse client-side.
It seems like this isn't a use case the AJAX Control Toolkit people had in mind, but I thought I'd check.

Write the following code in the OnClick event of Image/button
<asp:Image ID="img1" runat="server" OnClick="ExpandCollapse()"/>
function ExpandCollapse() {
$find("collapsibleBehavior1").set_Collapsed(true);
$find("collapsibleBehavior2").set_Collapsed(true);
}
Hope this helps!

I have a partly working solution now.
I followed Ian's suggestion and looked through the toolkit source. In CollapsiblePanelBehavior.debug.js, you can that expandPanel() is apparently intended as part of the public interface for the behavior. There's also a get_Collapsed(). The key to accessing these behaviors in javascript seems to be setting the BehaviorID property on your CollapsiblePanelExtender tags in ASP.NET.
I modified the repeater on my page so that the BehaviorIDs are predictible, along these lines:
<ajaxToolkit:CollapsiblePanelExtender
BehaviorID="<%#'collapsebehavior'+DataBinder.Eval(Container.DataItem,'id')%>"
ID="CollapsiblePanelExtender" runat="server" />
This results with behaviors named collapsebehavior1, collapsebehavior2, collapsebehavior3, etc..
With this done, I'm able to expand all the collapsible panels on the client as follows:
function expandAll() {
var i = 0;
while (true) {
i++;
var name = 'collapsebehavior' + i;
var theBehavior = $find(name);
if (theBehavior) {
var isCollapsed = theBehavior.get_Collapsed();
if (isCollapsed) {
theBehavior.expandPanel();
}
} else {
// No more more panels to examine
break;
}
}
}
I'm sure using $find in a loop like that is really inefficient, but that's what I have so far.
Also, it doesn't work on Firefox for some reason. (On FF only the first element expands, and then there's a Javascript error inside the Control Toolkit code.)
This will all seem extremely ugly to all you javascript pros. Maybe I'll clean things up later, or you can help me out.

You can also just toggle the panels to switch between collapsed/expanded states:
function toggle() {
var MenuCollapser = $find("name");
MenuCollapser.togglePanel();
}

Related

How to get user's input from WicketStuff's TinyMCE

Pretty straight-forward question, but I can't find this anywhere. I'm using WicketStuff's TinyMCE to make a Rich Text Editor in my application, and can't find anywhere how to get the input from the text area. For brevity's sake, the following is a simplified version of the code I'm using.
private String input;
...
TinyMCESettings settings = new TinyMCESettings(TinyMCESettings.Theme.simple);
TextArea<String> textArea = new TextArea<String>("editor", new PropertyModel<String>(this, "input"));
textArea.add(new TinyMceBehavior(settings));
form.add(textArea);
Using this, I would expect the usual manner to simply use my String 'input' since it's set as the model. This always results in null as the model isn't being updated.
I tried using the auto-save plugin in case it was expecting the save button to be clicked (which doesn't update the model either), and neither worked. The only thing I've been able to do to get the user's input is to add a HiddenField, with a new model, and make a JavaScript call like
document.getElementById('hiddenField').value = tinyMCE.get('editor').getContent();
but this has led to other problems with trying to call the JS in the desired place and to get it to work properly. I feel this shouldn't be necessary anyways, as surely someone must have implemented a method to get the contents of the text area being used.
Any help would be greatly appreciated.
Thanks to a blog post at Nevermind Solutions, the way to get the model updated is to add the following JavaScript to the form's submitting button:
onclick="tinyMCE.triggerSave(true,true);"
My text area is inside a panel with the button outside of the panel, so it doesn't directly work for me. The trick was to add the JavaScript call to the button's onSubmit, move the logic into the onAfterSubmit, and to make the button MultiPart so that it could call the save trigger before doing the other logic associated to the model.
Hope this might help some others in the future.
You have to add a modifier to the submit button so that the model can update.
AjaxButton btnSubmit = new AjaxButton("btnSubmit", new Model()) {
#Override
public void onSubmit(AjaxRequestTarget target, Form<?> form) {
doSomething();
}
};
btnSubmit.add(new TinyMceAjaxSubmitModifier());
Have a look here for more info

multiple instances of hide/show div on page

my div toggling script works if there is only one set of elements to toggle, but not when there are multiple instances per page. need multiple divs to toggle independently/separately.
http://jsfiddle.net/pixeloco/2zCe5/
$(function(){
$('.showFull').click(function() {
$('.targetDiv').hide();
$('#div' + $(this).data('target')).show();
});
});
because the final code will be output dynamically via the wordpress loop, a solution using data-id's (such as in this threads accepted answer How to create multiple instances of show/hide div in jquery?) appeals to me because i could populate that with the post id.
unfortunately i don't have enough JS knowledge to tweak that solution to fit my needs, hoping someone can help point me in the right direction. thanks!
Use Jquery traversing to go up to the parent 'storeitem' level and then work your way back down. This way, all the toggling stays within the given storeitem:
http://jsfiddle.net/2zCe5/1/
$(function(){
$('.showFull').click(function() {
$(this).parents('.storeitem').find('.targetDiv').hide();
$(this).parents('.storeitem').find('#div' + $(this).data('target')).show();
});
});
There's probably of more graceful way to write it but this is the idea.

How to handle UI animation events with knockout

So right now I have a table that displays some values and I have an indicator for conflicts. When the user clicks the indicator a new div appears with some animation to list all the conflicts.
Here is my HTML:
<span data-bind="if: hasConflict, click: $parent.selectProperty" class="conflictWarn"><i style="color: darkorange; cursor:pointer;" class="icon-warning-sign"></i></span>
The data might look something like this:
{
name:Property 1,
id: 1,
hasConflicts: no,
name:Property 2,
id: 2,
hasConflicts: yes,
conflicts: {
name: conflict1,
name: conflict2
}
name:Property 3,
id: 3,
hasConflicts: yes,
conflicts: {
name: conflicta,
name: conflictb
}
So the first table is going to look like this:
Property 1
Property 2 !
Property 3 !
Where ! is a conflict indicator. Clicking on the ! would display the conflicts div and also display conflict1 and conflict2 or conflicta and conflictb depending on which was clicked.
Here is the model we are working with. It's a bit complex because of the mapping for the properties from signalr. the "selectProperty" and "selectedProperty" was our way of saying which one to display conflicts for, but I'm not convinced this is the best way to do it.
function ItemViewModel() {
var self = this;
self.name = ko.observable("");
self.itemType = ko.observable("");
self.propertiesArray = ko.observableArray([]);
self.properties = ko.mapping.fromJS({});
self.selectedPropertyName = ko.observable("");
self.getItem = function (name) {
$.connection.mainHub.server.getItem(name).then(function (item) {
ko.mapping.fromJS(item.properties, self.properties);
self.propertiesArray(item.propertiesArray);
self.itemType(item.itemType.name);
self.name(item.name);
});
self.selectProperty = function (a, b) {
self.selectedPropertyName(a);
};
};
}
Originally the click event directly called a javascript function that did all the animation, but my coworker thought that might violate best practices for separating data and viewmodel in MVVM. Does it? Should we leave it calling the viewmodel function of "selectProperty" which allows us to pass context for the "conflicts popup" div? If so, do I just call the javascript function to do the animation from within the selectProperty function?
p.s. I've edited this about 800 times so I apologize if it's impossible to follow.
update I have the bindings working now, so I really just want to know what is best practice when it comes to UI animations and Knockout. Change the viewmodel from the javascript function or call the javascript function from the viewmodel function?
Regarding UI animations in my opinion it is best practice to implement custom bindings. This way code is encapsulated and it is easy to find where it is used. Check Animated transitions example on knockout website.
i'm going to extends Thomas answer with one point, custom bindings don't work when you want to animate the rendering / unrendering of the 'if' or 'with' bindings. an animation binding that tries to run at the same time as an 'if' or 'with' won't be able to complete the animation before the other binding alters the DOM, possibly removing the elements being animated from the page. there is no way to defer the binding processing until after the event completes.
for these cases animations should be implemented via the 'afterAdd' and 'beforeRemove' callbacks of the 'foreach' binding when the desire is to animate an element being added and removed from the page. 'if' and 'with' bindings can be rewritten as 'foreach' with little effort, as 'foreach' can take a single argument instead of a list. i really wish the animation tutorial would be extended to include this workaround.

Zend Form Element with Javascript - Decorator, View Helper or View Script?

I want to add some javacsript to a Zend_Form_Element_Text .
At first I thought a decorator would be the best way to do it, but since it is just a script (the markup doesn't change) then maybe a view helper is better? or a view script?
It seems like they are all for the same purpose (regarding a form element).
The javascript I want to add is not an event (e.g. change, click, etc.). I can add it easily with headScript() but I want to make it re-usable , that's why I thought about a decorator/view helper. I'm just not clear about the difference between them.
What is the best practice in this case? advantages?
UPDATE: Seems like the best practice is to use view helpers from view scripts , so decorators would be a better fit?
Thanks.
You could create your own decorator by extending Zend_From_Decorator_Abstract and generate your snippet in it's render() method :
class My_Decorator_FieldInitializer extends Zend_Form_Decorator_Abstract {
public function render($content){
$separator = $this->getSeparator();
$element = $this->getElement();
$output = '<script>'.
//you write your js snippet here, using
//the data you have in $element if you need
.'</script>';
return $content . $separator . $output;
}
}
If you need more details, ask for it in a comment, i'll edit this answer. And I didn't test this code.
Use setAttrib function.
eg:-
$element = new Zend_Form_Element_Text('test');
$element->setAttrib('onclick', 'alert("Test")');
I'm not actually seeing where this needs to be a decorator or a view-helper or a view-script.
If I wanted to attach some client-side behavior to a form element, I'd probably set an attribute with $elt->setAttrib('class', 'someClass') or $elt->setAttrib('id', 'someId'), some hook onto which my script can attach. Then I'd add listeners/handlers to those targeted elements.
For example, for a click handler using jQuery , it would be something like:
(function($){
$(document).ready(function(){
$('.someClass').click(function(e){
// handle the event here
});
});
})(jQuery);
The benefit is that it is unobtrusive, so the markup remains clean. Hopefully, the javascript is an enhancement- not a critical part of the functionality - so it degrades gracefully.
Perhaps you mean that this javascript segment itself needs to be reusable across different element identifiers - someClass, in this example. In this case, you could simply write a view-helper that accepts the CSS class name as the parameter.
"the markup doesn't change", Yap,
but I like to add some javascript function throw ZendForm Element:
$text_f = new Zend_Form_Element_Text("text_id");
$text_f->setAttrib('OnChange', 'someFunction($(this));');
The best way is if you are working with a team, where all of you should use same code standard. For me and my team this is the code above.

getBoundingClientRect() is returning zero in XUL

I have a problem with my firefox extension
I have a XUL popup panel with a hbox for the tag cloud, and a JS code to add divs to this hbox:
<hbox id="tag_base" ondblclick="alert('done')"/>
JS:
var root = document.getElementById('tag_base');
var tag = document.createElement('div');
tag.textContent = 'test';
root.appendChild(tag);
var rect = tag.getBoundingClientRect()
alert(rect.top)
I need to get the dimensions of each added div, however, getBoundingClientRect simply refuses to work.
If I remove alerts, it's always zero.
With alerts the story is different:
The first time the alert is called it returns zero, although the div appears on the screen.
Any subsequent alerts return the correct coordinates.
If I set a breakpoint in Chromebug, everything is reported correctly.
If I do not interupt the execution in any way, and run a loop, only zeroes got returned.
This has got me quite confused.
Calling "boxObject" produces the same results, while "getClientRects[0]" is undefined on the first call.
Any hints on what might be causing this will be greatly appreciated.
Note :
Caution, if you use getBoundingClientRect with an element which has display:none then it will return 0, anywhere in the dom.
Although I can't find any documentation on this seemingly fundamental issue, the problem you noticed is most likely because the layout (aka "reflow") process has not yet run by the moment you ask for the coordinates.
The layout/reflow process takes the page's DOM with any styles the page has and determines the positions and dimensions of the elements and other portions of the page (you could try to read Notes on HTML reflow, although it's not targeted at web developers and probably is a bit outdated).
This reflow process doesn't run synchronously after any change to the DOM, otherwise code like
elt.style.top = "5px";
elt.style.left = "15px";
would update the layout twice, which is inefficient.
On the other hand, asking for elements position/dimension (at least via .offsetTop) is supposed to force layout to return the correct information. This doesn't happen in your case for some reason and I'm not sure why.
Please create a simple testcase demonstrating the problem and file a bug in bugzilla.mozilla.org (CC me - ***********#gmail.com).
My guess is that this is related to XUL layout, which is less robust than HTML; you could try creating the cloud in an HTML doc in an iframe or at least in a <description> using createElementNS to create real HTML elements instead of xul:div you're creating with your current code.
Be sure the DOM is ready. In my case, even when using the getBoundingClientRect function on click events. The binding of the events needed to happen when the DOM is ready.