ZK Customize Calender Popup - javascript

I want to add clear button in Calender modal Popup.In my application lots of dateboxes are there.I restrict the user only to select the date not to enter. But in some cases I need to clear the date. Because of read only I am not able to clear it manually. I need to customize the calender which will reflect other places. And user can clear the datebox by clicking clear button in calender window.
Is there any way to add clear button in calender to fulfill my requirement?
Thanks in Advance!!

You can customize widget action with Client Side Programming (refer to Client Side Programming), for example:
<zk xmlns:w="client">
<!-- -->
<!-- Tested with ZK 6.5.3 -->
<!-- -->
<zscript><![CDATA[
// testing data
Date d = new Date();
]]></zscript>
<style>
/* invisible if not moved into datebox */
.invisible {
display: none !important;
}
</style>
put clear button under popup of datebox
<button label="show value" onClick="alert(((Datebox)self.getNextSibling()).getValue());" />
<datebox readonly="true" value="${d}">
<attribute w:name="doClick_"><![CDATA[
function (evt) {
// call original function
this.$doClick_(evt);
var pp = this.$n('pp'), // popup dom
$n = jq(this.$n()); // root dom
if (pp && !jq(pp).find('.datebox-inner-clear-button')[0]) {
// find button next to root dom
var btn = $n.next('.datebox-inner-clear-button')[0], // button dom element
btnWgt = zk.Widget.$('#' + btn.id), // button widget
popupWgt = this._pop;
// make button visible
jq(btn).removeClass('invisible');
// put button under popup dom
pp.appendChild(btn);
// store self at button widget
btnWgt.datebox = this;
var oldOnFloatUp = popupWgt.onFloatUp;
popupWgt.onFloatUp = function (ctl) {
if(ctl.origin == btnWgt) return; // do not close popup while mousedown on button
oldOnFloatUp.apply(this, arguments);
}
}
}
]]></attribute>
</datebox>
<button label="clear" sclass="datebox-inner-clear-button invisible">
<attribute w:name="doClick_"><![CDATA[
function (evt) {
// call original function
this.$doClick_(evt);
var dbx = this.datebox;
if (dbx) {
dbx.getInputNode().value = '';
dbx.updateChange_();
}
}
]]></attribute>
</button>
</zk>
You may also want to wrap the customized datebox and button by Macro Component or Composite Component as needed.

Related

Duplicate HTML in jQuery into a BootStrap Modal

The function below is called after an icon is clicked, which creates a modal. During the function, I traverse up the DOM, grab a HTML canvas and display it in the modal. The problem I am having is that it is removing the HTML I grab initially, I want it to be duplicated. Can anyone shed some light on this?
JS:
$('#chartModal').on('show.bs.modal', function (event) {
console.log('yeppp');
// Button that triggered the modal
const button = $(event.relatedTarget)
// Get corresponding chart's HTML
const chart = button.parent().next()[0]
var modal = $(this)
// Update modal's content with the corresponding chart
modal.find('.modal-body').html(chart)
})
Regards,
James.
Since you are using jQuery, you can use the .clone() method like so:
$('#chartModal').on('show.bs.modal', function (event) {
// Button that triggered the modal
var button = $(event.relatedTarget);
// Get corresponding chart's HTML
// "chart" is a plain node here
var chart = button.parent().next()[0];
var modal = $(this);
// Update modal's content with the corresponding chart
modal.find('.modal-body').html($(chart).clone());
})
// OR
$('#chartModal').on('show.bs.modal', function (event) {
// Button that triggered the modal
var button = $(event.relatedTarget);
// Get corresponding chart's HTML
// "chart" is now a jQuery object
var chart = button.parent().next();
var modal = $(this);
// Update modal's content with the corresponding chart
modal.find('.modal-body').html(chart.clone());
})
Your current code snippet seems overly complicated in my opinion.
Here's a different solution that might be easier to follow:
HTML:
...
<canvas class="one-of-my-charts"></canvas>
...
JS:
$('.one-of-my-charts').click(function(e) {
$('#the-chart-modal').html(e.target);
$('#the-chart-modal').modal('show');
});

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

Prevent background items from receiving focus while modal overlay is covering them?

I am working on making an overlay modal more accessible. It works essentially like this JSFiddle. When you open the modal, the focus doesn't properly go into the modal, and it continues to focus on other (hidden, background) items in the page.
You can see in my JSFiddle demo that I have already used aria-controls, aria-owns, aria-haspopup and even aria-flowto.
<button
aria-controls="two"
aria-owns="true"
aria-haspopup="true"
aria-flowto="two"
onclick="toggleTwo();"
>
TOGGLE DIV #2
</button>
However, while using MacOS VoiceOver, none of these do what I intend (though VoiceOver does respect the aria-hidden that I set on div two).
I know that I could manipulate the tabindex, however, values above 0 are bad for accessibility, so my only other option would be to manually find all focusable elements on the page and set them to tabindex=-1, which is not feasible on this large, complicated site.
Additionally, I've looked into manually intercepting and controlling tab behavior with Javascript, so that the focus is moved into the popup and wraps back to the top upon exiting the bottom, however, this has interfered with accessibility as well.
Focus can be moved with the focus() method. I've updated the jsFiddle with the intended behavior. I tested this on JAWS on Windows and Chrome.
I've added a tabindex="-1" on the "two" div to allow it to be focusable with the focus method.
I split the toggle function into two functions, this can probably be refactored to fit your needs, but one function sets the aria-hidden attribute to true and moves the focus on the newly opened modal, and the other function does the reverse.
I removed the excessive aria attributes, the first rule of aria is to only use it when necessary. This can cause unexpected behavior if you're just mashing in aria.
To keep focus within the modal, unfortunately one of the best options is to set all other active elements to tabindex="-1" or aria-hidden="true". I've applied an alternative where an event listener is added to the last element in the modal upon tabbing. To be compliant, another listener must be added to the first element to move focus to the last element upon a shift+tab event.
Unfortunately, to my knowledge there isn't a cleaner answer than those above solutions to keeping focus within a modal.
Use role = "dialog" aria-modal="true" on your modal popup
aria-disabled vs aria-hidden
First, note that aria-hidden is not intended to be used when the element is visible on the screen:
Indicates that the element and all of its descendants are not visible or perceivable to any user
The option you should use is aria-disabled
Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
on using tabindex
Removing a link from the tabindex is a WCAG failure if this link is still perceivable from a screenreader or clickable. It has to be used conjointly with aria-disabled or better the disabled attribute.
Disabling mouse events using pointer-events css property
The easiest way to disable mouse events is by using the pointer-events css property:
pointer-events: none;
Disabling keyboard focus
The jQuery :focusable selecter is the easiest thing you could use
$("#div1 :focusable").attr("tabindex", -1);
sample code
$("#div1 :focusable")
.addClass("unfocus")
.attr("tabindex", -1)
.attr("disabled", true);
$("button").on("click", function(){
$(".unfocus").attr("tabindex", 0)
.removeClass("unfocus")
.removeAttr("disabled");
});
.unfocus {
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div id="div1">
non clickable link
<div tabindex="0">
non focusable div
</div>
</div>
<div id="div2">
<button>click here to restore other links</button>
</div>
Make the first and the last focusable element of your modal react on event, resp. on pressing tab and shift+tab. As far as I tested, it works everywhere.
Example:
function createFocusCycle (first, last) {
first.addEventListener('keydown', function(e){
if (e.keyCode===9 && e.shiftKey) {
last.focus();
e.preventDefault();
}});
last.addEventListener('keydown', function(e){
if (e.keyCode===9) {
first.focus();
e.preventDefault();
}});
}
Naturally, you need to know what is the first and the last focusable element of your modal. Normally it shouldn't be too complicated.
Otherwise if you don't know what are the first and last focusable elements of your modal, it's perhaps a sign that you are making a too complex UI.
In the future this could be solved with the inert attribute: https://github.com/WICG/inert/blob/7141197b35792d670524146dca7740ae8a83b4e8/explainer.md
I used this solution of focusguard element that focus on it moves the focus to the desired element, using JS.
Found it here:
https://jsfiddle.net/dipish/F82Xj/
<p>Some sample content here...</p>
<p>Like, another <input type="text" value="input" /> element or a <button>button</button>...</p>
<!-- Random content above this comment -->
<!-- Special "focus guard" elements around your
if you manually set tabindex for your form elements, you should set tabindex for the focus guards as well -->
<div class="focusguard" id="focusguard-1" tabindex="1"></div>
<input id="firstInput" type="text" tabindex="2" />
<input type="text" tabindex="3" />
<input type="text" tabindex="4" />
<input type="text" tabindex="5" />
<input type="text" tabindex="6" />
<input id="lastInput" type="text" tabindex="7" />
<!-- focus guard in the end of the form -->
<div class="focusguard" id="focusguard-2" tabindex="8"></div>
<!-- Nothing underneath this comment -->
JS:
$('#focusguard-2').on('focus', function() {
$('#firstInput').focus();
});
$('#focusguard-1').on('focus', function() {
$('#lastInput').focus();
});
As far as I know, there is no native HTML aria support to get back the same focus when a modal is closed.
aria-modal is going to replace aria-hidden. It should used in combination with role="alertdialog". This www.w3.org/TR/wai-aria-practices-1.1 page explains what they do and offers a complex example. Inspired by this, I made a minimal snippet.
Never use tabindex higher than 0. tabindex="0" is set to the modals heading. So it gets focused with the tab key. The opening button is saved in a variable lastFocusedElement. When the modal is closed, the focus gets back to there.
window.onload = function () {
var lastFocusedElement;
// open dialog
document.querySelector('#open-dialog').addEventListener('click', (e) => {
document.querySelector('#dialog').classList.add('d-block');
document.querySelector('#backdrop').classList.add('d-block');
lastFocusedElement = e.currentTarget;
});
// close dialog and back to last focused element
document.querySelector('#close-dialog').addEventListener('click', (e) => {
document.querySelector('#dialog').classList.remove('d-block');
document.querySelector('#backdrop').classList.remove('d-block');
lastFocusedElement.focus();
});
}
h2 { font-size: 1em }
.d-block {
display: block !important;
}
.dialog {
display: none;
position: fixed;
top: 1rem;
width: 25rem;
padding: 1rem;
background: #fff;
border: 1px solid #000;
z-index: 1050;
font-family: arial, sans-serif;
font-size: .8em;
}
#backdrop {
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 1040;
background: rgba(0, 0, 0, 0.5);
}
<label for="just-a-label">Just a label</label>
<button id="open-dialog" type="button" aria-labelledby="just-a-label">open dialog</button>
<div id="dialog" class="dialog" role="alertdialog" aria-modal="true" aria-labelledby="dialog-label" aria-describedby="dialog-desc">
<h2 id="dialog-label" tabindex="0">PRESS TAB to get here</h2>
<div id="dialog-desc">
<p>Dialog Description.</p>
</div>
<div>
<label for="formfield">
<span>another formfield:</span>
<input id="formfield" type="text">
</label>
</div>
<hr>
<div>
<button id="close-dialog" type="button" tabindex="0">CLOSE (and focus back to open button)</button>
</div>
</div>
<div id="backdrop"></div>
I know it's a little late but that's how I resolve the issue of background focus on the modal. I will provide two solutions one for "talkback" and another one is for "Switch Access" which will work for the tab key too.
For Talkback:
function preventFocusOnBackground(ariaHide) {
$("body > *").not("#modalId").attr("aria-hidden", ariaHide);
}
// when you close the modal
preventFocusOnBackground(false);
// when you open the modal
preventFocusOnBackground(true)
For Switch Access/Control copy/paste this code in your file:
var aria = aria || {};
aria.Utils = aria.Utils || {};
(function () {
/*
* When util functions move focus around, set this true so the focus
listener
* can ignore the events.
*/
aria.Utils.IgnoreUtilFocusChanges = false;
aria.Utils.dialogOpenClass = 'has-dialog';
/**
* #desc Set focus on descendant nodes until the first focusable
element is
* found.
* #param element
* DOM node for which to find the first focusable descendant.
* #returns
* true if a focusable element is found and focus is set.
*/
aria.Utils.focusFirstDescendant = function (element) {
for (var i = 0; i < element.childNodes.length; i++) {
var child = element.childNodes[i];
if (aria.Utils.attemptFocus(child) ||
aria.Utils.focusFirstDescendant(child)) {
return true;
}
}
return false;
}; // end focusFirstDescendant
/**
* #desc Find the last descendant node that is focusable.
* #param element
* DOM node for which to find the last focusable descendant.
* #returns
* true if a focusable element is found and focus is set.
*/
aria.Utils.focusLastDescendant = function (element) {
for (var i = element.childNodes.length - 1; i >= 0; i--) {
var child = element.childNodes[i];
if (aria.Utils.attemptFocus(child) ||
aria.Utils.focusLastDescendant(child)) {
return true;
}
}
return false;
}; // end focusLastDescendant
/**
* #desc Set Attempt to set focus on the current node.
* #param element
* The node to attempt to focus on.
* #returns
* true if element is focused.
*/
aria.Utils.attemptFocus = function (element) {
if (!aria.Utils.isFocusable(element)) {
return false;
}
aria.Utils.IgnoreUtilFocusChanges = true;
try {
element.focus();
}
catch (e) {
}
aria.Utils.IgnoreUtilFocusChanges = false;
return (document.activeElement === element);
}; // end attemptFocus
/* Modals can open modals. Keep track of them with this array. */
aria.OpenDialogList = aria.OpenDialogList || new Array(0);
/**
* #returns the last opened dialog (the current dialog)
*/
aria.getCurrentDialog = function () {
if (aria.OpenDialogList && aria.OpenDialogList.length) {
return aria.OpenDialogList[aria.OpenDialogList.length - 1];
}
};
aria.Utils.isFocusable = function(element) {
return element.classList && element.classList.contains('focusable');
}
aria.closeCurrentDialog = function () {
var currentDialog = aria.getCurrentDialog();
if (currentDialog) {
currentDialog.close();
return true;
}
return false;
};
document.addEventListener('keyup', aria.handleEscape);
/**
* #constructor
* #desc Dialog object providing modal focus management.
*
* Assumptions: The element serving as the dialog container is present
in the
* DOM and hidden. The dialog container has role='dialog'.
*
* #param dialogId
* The ID of the element serving as the dialog container.
* #param focusAfterClosed
* Either the DOM node or the ID of the DOM node to focus
* when the dialog closes.
* #param focusFirst
* Optional parameter containing either the DOM node or the
ID of the
* DOM node to focus when the dialog opens. If not specified, the
* first focusable element in the dialog will receive focus.
*/
aria.Dialog = function (dialogId, focusAfterClosed, focusFirst) {
this.dialogNode = document.getElementById(dialogId);
if (this.dialogNode === null) {
throw new Error('No element found with id="' + dialogId + '".');
}
var validRoles = ['dialog', 'alertdialog'];
var isDialog = (this.dialogNode.getAttribute('role') || '')
.trim()
.split(/\s+/g)
.some(function (token) {
return validRoles.some(function (role) {
return token === role;
});
});
if (!isDialog) {
throw new Error(
'Dialog() requires a DOM element with ARIA role of dialog or
alertdialog.');
}
// Wrap in an individual backdrop element if one doesn't exist
// Native <dialog> elements use the ::backdrop pseudo-element, which
// works similarly.
var backdropClass = 'dialog-backdrop';
if (this.dialogNode.parentNode.classList.contains(backdropClass)) {
this.backdropNode = this.dialogNode.parentNode;
}
else {
this.backdropNode = document.createElement('div');
this.backdropNode.className = backdropClass;
this.dialogNode.parentNode.insertBefore(this.backdropNode,
this.dialogNode);
this.backdropNode.appendChild(this.dialogNode);
}
this.backdropNode.classList.add('active');
// Disable scroll on the body element
document.body.classList.add(aria.Utils.dialogOpenClass);
if (typeof focusAfterClosed === 'string') {
this.focusAfterClosed = document.getElementById(focusAfterClosed);
}
else if (typeof focusAfterClosed === 'object') {
this.focusAfterClosed = focusAfterClosed;
}
else {
throw new Error(
'the focusAfterClosed parameter is required for the aria.Dialog
constructor.');
}
if (typeof focusFirst === 'string') {
this.focusFirst = document.getElementById(focusFirst);
}
else if (typeof focusFirst === 'object') {
this.focusFirst = focusFirst;
}
else {
this.focusFirst = null;
}
// If this modal is opening on top of one that is already open,
// get rid of the document focus listener of the open dialog.
if (aria.OpenDialogList.length > 0) {
aria.getCurrentDialog().removeListeners();
}
this.addListeners();
aria.OpenDialogList.push(this);
this.clearDialog();
this.dialogNode.className = 'default_dialog'; // make visible
if (this.focusFirst) {
this.focusFirst.focus();
}
else {
aria.Utils.focusFirstDescendant(this.dialogNode);
}
this.lastFocus = document.activeElement;
}; // end Dialog constructor
aria.Dialog.prototype.clearDialog = function () {
Array.prototype.map.call(
this.dialogNode.querySelectorAll('input'),
function (input) {
input.value = '';
}
);
};
/**
* #desc
* Hides the current top dialog,
* removes listeners of the top dialog,
* restore listeners of a parent dialog if one was open under the one
that just closed,
* and sets focus on the element specified for focusAfterClosed.
*/
aria.Dialog.prototype.close = function () {
aria.OpenDialogList.pop();
this.removeListeners();
aria.Utils.remove(this.preNode);
aria.Utils.remove(this.postNode);
this.dialogNode.className = 'hidden';
this.backdropNode.classList.remove('active');
this.focusAfterClosed.focus();
// If a dialog was open underneath this one, restore its listeners.
if (aria.OpenDialogList.length > 0) {
aria.getCurrentDialog().addListeners();
}
else {
document.body.classList.remove(aria.Utils.dialogOpenClass);
}
}; // end close
/**
* #desc
* Hides the current dialog and replaces it with another.
*
* #param newDialogId
* ID of the dialog that will replace the currently open top dialog.
* #param newFocusAfterClosed
* Optional ID or DOM node specifying where to place focus when the
new dialog closes.
* If not specified, focus will be placed on the element specified by
the dialog being replaced.
* #param newFocusFirst
* Optional ID or DOM node specifying where to place focus in the new
dialog when it opens.
* If not specified, the first focusable element will receive focus.
*/
aria.Dialog.prototype.replace = function (newDialogId,
newFocusAfterClosed,
newFocusFirst) {
var closedDialog = aria.getCurrentDialog();
aria.OpenDialogList.pop();
this.removeListeners();
aria.Utils.remove(this.preNode);
aria.Utils.remove(this.postNode);
this.dialogNode.className = 'hidden';
this.backdropNode.classList.remove('active');
var focusAfterClosed = newFocusAfterClosed || this.focusAfterClosed;
var dialog = new aria.Dialog(newDialogId, focusAfterClosed,
newFocusFirst);
}; // end replace
aria.Dialog.prototype.addListeners = function () {
document.addEventListener('focus', this.trapFocus, true);
}; // end addListeners
aria.Dialog.prototype.removeListeners = function () {
document.removeEventListener('focus', this.trapFocus, true);
}; // end removeListeners
aria.Dialog.prototype.trapFocus = function (event) {
if (aria.Utils.IgnoreUtilFocusChanges) {
return;
}
var currentDialog = aria.getCurrentDialog();
if (currentDialog.dialogNode.contains(event.target)) {
currentDialog.lastFocus = event.target;
}
else {
aria.Utils.focusFirstDescendant(currentDialog.dialogNode);
if (currentDialog.lastFocus == document.activeElement) {
aria.Utils.focusLastDescendant(currentDialog.dialogNode);
}
currentDialog.lastFocus = document.activeElement;
}
}; // end trapFocus
window.openDialog = function (dialogId, focusAfterClosed, focusFirst){
var dialog = new aria.Dialog(dialogId, focusAfterClosed,focusFirst);
};
window.closeDialog = function (closeButton) {
var topDialog = aria.getCurrentDialog();
if (topDialog.dialogNode.contains(closeButton)) {
topDialog.close();
}
}; // end closeDialog
window.replaceDialog = function (newDialogId, newFocusAfterClosed,
newFocusFirst) {
var topDialog = aria.getCurrentDialog();
if (topDialog.dialogNode.contains(document.activeElement)) {
topDialog.replace(newDialogId, newFocusAfterClosed,newFocusFirst);
}
}; // end replaceDialog
}());
And call it where you open the modal like this:
openDialog('modalID', this);
Add these attributes in the modal div tag:
<div id="modalId" aria-modal="true" role="dialog">
Add "tabindex" attributes on all the elements where you want the focus. Like this:
<a href="#" onclick="resizeTextFixed(1.4);return false;" tabindex="1"
aria-label="Some text">A</a>
<a href="#" onclick="resizeTextFixed(1.2);return false;" tabindex="2"
aria-label="Some text">A</a>
Add "focusable" class to the first focusable element:
<div class="focuable"></div>
That's it.
I found a very simple vanillaJS solution that should work in any modern browser:
const container=document.querySelector("#yourIDorwhatever")
//optional: needed only if the container element is not focusable already
container.setAttribute("tabindex","0")
container.addEventListener("focusout", (ev)=>{
if (ev.relatedTarget && !container.contains(ev.relatedTarget)) container.focus()
})
The mode of operation is very simple:
makes the container focusable, if not already
adds an event listener to the focusout event which fires when the focus is about to go outside of the container
Checks if the next target of the focus is in fact outside of the container, and if so, then puts the focus back to the container itself
The last check is needed because the focusout event also fires when the focus moves from one element to the another within the container.
Note: the focus can leave the page, eg the address bar of the browser. This doesn't seem to be preventable - at least according to my testing in Chrome.

Link add-on SDK panel to toolbar button

The add-on SDK attaches panels to widgets as seen here. I would like to achieve the same effect using the add-on SDK with a toolbar button instead.
The toolbar button I'm using is of the type menu-button, which means that the left side is an icon and has an oncommand listener. The right side is a drop-down arrow which shows its contents on click. Here's the code to create such a button with the add-on SDK:
const doc = require('sdk/window/utils').getMostRecentBrowserWindow().document;
var navBar = doc.getElementById('nav-bar')
var btn = doc.createElement('toolbarbutton');
btn.setAttribute('id', 'hylytit');
btn.setAttribute('type', 'menu-button');
btn.setAttribute('class', 'toolbarbutton-1');
btn.setAttribute('image', data.url('resources/hylyt_off.png'));
btn.setAttribute('orient', 'horizontal');
btn.setAttribute('label', 'Hylyt.it');
btn.addEventListener('command', function(event) {
if (event.button===0) btnClick();
console.log(TAG+'button clicked');
}, false);
var panel = doc.createElement('panel');
panel.setAttribute('id', 'search-panel');
panel.addEventListener('command', function(event) {
console.log(TAG+'dropdown clicked');
}, false);
var label = doc.createElement('label');
label.setAttribute('control', 'name');
label.setAttribute('value', 'Article List');
var textbox = doc.createElement('textbox');
textbox.setAttribute('id', 'name');
panel.appendChild(label);
panel.appendChild(textbox);
btn.appendChild(panel);
navBar.appendChild(btn);
The panel above is not an add-on SDK panel, it's a XUL panel and is severely limited in that it can't be styled with CSS. On top of this, the panel's onCommand listener never fires despite the fact that the btn's onCommand fires as expected. The XUL panel shows itself when I click the dropdown button (as long as it has children), but because I can't access its click handler, I can't just create an add-on SDK panel on click.
So my question is this. Is there a way to access the toolbar button's menu portion's click handler or is there a way to append an add-on SDK panel as a child of a toolbar button?
Thanks for pointing me in the direction of arrow panels. Is there a way to place an HTML file in one rather than having to dynamically create XUL elements? The effect I'm trying to achieve is similar to the Pocket extension, which does one thing when the button part is clicked and another when the arrow is clicked. – willlma 7 hours ago
You have 900+ rep, you should know better. It is common knowledge to create another question topic rather then ask how to do something different in a comment especially after solution acceptance.
Nonetheless, this is what you do to accomplish the Pocket toolbarbutton effect. Based on code supplied by contributor above.
Ask another question and I'll move this there and you can accept my solution there.
var doc = document;
var navBar = doc.getElementById('nav-bar')
var btn = doc.createElement('toolbarbutton');
btn.setAttribute('id', 'hylytit');
btn.setAttribute('type', 'menu-button');
btn.setAttribute('class', 'toolbarbutton-1');
btn.setAttribute('image', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAYAAADtc08vAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDowMjgwMTE3NDA3MjA2ODExODcxRjlGMzUzNEZGQkNGQiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoxRUM5MTQ0MkJFNkUxMUUxOUM3NzgwMzc3MDc2Rjk1MCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoxRUM5MTQ0MUJFNkUxMUUxOUM3NzgwMzc3MDc2Rjk1MCIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MDI4MDExNzQwNzIwNjgxMTg3MUZFQTk0QUU4RTMwMEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MDI4MDExNzQwNzIwNjgxMTg3MUY5RjM1MzRGRkJDRkIiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5kJv/fAAAByUlEQVR42qRTPWvCYBC+mKiolFYURVSwfoCLkw4iGDM5WoO460/o4tKuHToV+gd0t5Ku4mQWJ8Fd/NhEpy6K3+ldakKsi+ALb3hzd89zd8+9L6MoCtyyOPpkMpl3m81WM5lMV4GOxyOsVqu3Xq/3qhIEg8Ga1+sFs9l8FcFut4P5fP6Cxz8CAvt8PmBZ9iqCw+Ggn9WaKTOB9/s9FAoF4Hn+LIjOZCMfxVGrWrWcFkRiWiwWiMfjIv6GOI77kGUZ1us15PN5SKVSz2ifttvtL2yBPRNRI1gsFiCK4pMkSVUE/GBrn5vN5i4ajVYxpFEsFuuRSIR1u91wQcAwDOAkwOl0VjBjCIFit9sdoOshl8sNsLp6IBCoOBwOME5LJSABqU8i8Pv91Kcwm83kdDrNk9/lcslYTYLi7HY7aBidIJvNTjqdziNpQBmIBDVIoFDT05TuPR6PCqbs2+0WBEGYqJWfbmKx2WxKo9FIDSAbtgDL5VLNQqRWq1Vtky4R6gDlcpnE/mYMV7nearUqw+FQJzEuDRyLxaBUKjXQVDVWoJNgFZV+vw/j8VgXi4DhcBiSySRl18H6+P5tAbekXC7p5DuLZ259jb8CDAAxmdyX9iaHkQAAAABJRU5ErkJggg==');
btn.setAttribute('orient', 'horizontal');
btn.setAttribute('label', 'Hylyt.it');
////
var toolbarbuttonPanel = doc.createElement('panel');
toolbarbuttonPanel.setAttribute('id', 'toolbarbutton-panel');
toolbarbuttonPanel.setAttribute('type', 'arrow');
var toolbarbuttonLabel = doc.createElement('label');
toolbarbuttonLabel.setAttribute('value', 'toolbarbutton panel');
toolbarbuttonPanel.appendChild(toolbarbuttonLabel);
////
////
var dropmarkerPanel = doc.createElement('panel');
dropmarkerPanel.setAttribute('id', 'dropmarker-panel');
dropmarkerPanel.setAttribute('type', 'arrow');
var dropmarkerLabel = doc.createElement('label');
dropmarkerLabel.setAttribute('value', 'dropmarker panel');
dropmarkerPanel.appendChild(dropmarkerLabel);
////
navBar.appendChild(btn);
var mainPopupSet = document.querySelector('#mainPopupSet');
mainPopupSet.appendChild(dropmarkerPanel);
mainPopupSet.appendChild(toolbarbuttonPanel);
btn.addEventListener('click',function(event) {
console.log('event.originalTarget',event.originalTarget);
if (event.originalTarget.nodeName == 'toolbarbutton') {
dropmarkerPanel.openPopup(btn);
} else if (event.originalTarget.nodeName == 'xul:toolbarbutton') {
toolbarbuttonPanel.openPopup(btn);
}
}, false);
Panels don't have an onCommand method see MDN - Panels Article
You can make your panel stylized, give it type arrow like panel.setAttribute('type', 'arrow') and then to attach to your button. I didn't give it type arrow below.
Heres the working code. Copy paste to scratchpad and set Environment > Browser then run it.
var doc = document; //to put this back in sdk do const doc = require('sdk/window/utils').getMostRecentBrowserWindow().document;
var navBar = doc.getElementById('nav-bar')
var btn = doc.createElement('toolbarbutton');
btn.setAttribute('id', 'hylytit');
btn.setAttribute('type', 'menu-button');
btn.setAttribute('class', 'toolbarbutton-1');
btn.setAttribute('image', ''); //i made this image blank because i dont have the image and im running from scratchpad
btn.setAttribute('orient', 'horizontal');
btn.setAttribute('label', 'Hylyt.it');
var panel = doc.createElement('panel');
btn.addEventListener('command', function(event) { //moved this below var panel = doc.createElement because panel needs to be crated before we write this function
//if (event.button===0) btnClick();
//console.log(TAG+'button clicked'); //what is TAG? its undefeined for me
panel.openPopup(btn);
}, false);
panel.setAttribute('id', 'search-panel');
/*
panel.addEventListener('command', function(event) {
console.log(TAG+'dropdown clicked'); //what is TAG? its undefeined for me
}, false);
*/
var label = doc.createElement('label');
label.setAttribute('control', 'name');
label.setAttribute('value', 'Article List');
var textbox = doc.createElement('textbox');
textbox.setAttribute('id', 'name');
panel.appendChild(label);
panel.appendChild(textbox);
btn.appendChild(panel);
navBar.appendChild(btn);
You can create a Toolbarbutton and Panel using the Addon SDK and some Jetpack modules. Try toolbarwidget-jplib and browser-action-jplib by Rob--W.
You can easy add a button to the toolbar and style the panel whatever you want with css / html:
var badge = require('browserAction').BrowserAction({
default_icon: 'images/icon19.png', // optional
default_title: 'Badge title', // optional; shown in tooltip
default_popup: 'popup.html' // optional
});

Dojo: Dijit loses selection after cloning their <div> containers

As a Dojo newbie, I am trying to create a simple wizard of pages using a plain JS array as a stack that I push and pop the cloned main content DOM node onto and off (without using the StackContainer)
The problem is that when I go back to a previous page and 'repopulate' the page with the cloned main content node popped off the stack, the controls (in this example code, the radio buttons, but I have similar problem with selecting rows in a DataGrid dijit that I'm not showing but is more of importance for my app) appears to be the same as I previously saw (e.g. the radio button is the same one as I previously selected). But
I can't seem to interact with them, e.g. couldn't select the other radio button at all
Neither control is, in fact, selected, despite of the page appearance.
If I change these radio buttons from dijits to plain html input controls, there is no such problem.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" type="text/css"
href="../dojo/dijit/themes/dijit.css">
<link rel="stylesheet" type="text/css"
href="../dojo/dijit/themes/soria/soria.css">
<title>TestSimplerStillS1</title>
<script>dojoConfig = {parseOnLoad: true}</script>
<script src='../dojo/dojo/dojo.js'></script>
<script>
// The stack used for the wizard
var mainContentStack=[]
dojo.ready(function(){
// Reset the stack
mainContentStack=[];
// Add the radio btns
var radioData11 = {value: "Radio1.1", label: "Radio1.1_lbl"};
var radioData12 = {value: "Radio1.2", label: "Radio1.2_lbl"};
populateNextPageRadioBtns("radios1", [radioData11, radioData12]);
// disable the back btn for the first page
dojo.byId("backBtn").disabled=true;
});
function onNextClicked() {
// Push the main content onto a stack to store
pushCloneOnStack();
// Find the selected radio btn and display it
displaySelectedRadio();
// Clear the existing radio btns
destroyAll("rdbtns_div_id");
// disable the next btn for the last page
dojo.byId("nextBtn").disabled=true;
}
function displaySelectedRadio() {
var rdDivs = dojo.byId("rdbtns_div_id").children;
for (var i = 0; i < rdDivs.length; i++) {
rdDiv = rdDivs[i];
if (rdDiv !== null) {
var rd = rdDiv.children[0].children[0];
if (rd.checked) {
dojo.byId("rdbtns_sel_div_id").innerHTML=rd.value;
}
}
}
}
function onBackClicked() {
popAndAssignFromStack();
}
function destroyAll(nodeId){
var wContainers = dojo.byId(nodeId);
dojo.forEach(dijit.findWidgets(wContainers), function(w) {
w.destroyRecursive(false);
});
dojo.byId(nodeId).innerHTML = "";
}
function populateNextPageRadioBtns(grpIdentifier, radioBtnDataArray){
// Create new radio btns
require(['dojo/_base/array'], function(array){
var i = 0;
array.forEach(radioBtnDataArray, function(radioBtnData){
// Create the radio btns and default the 1st radio btn to be checked
createRadioBtn(grpIdentifier, radioBtnData, (i==0));
i++;
});
});
}
function createRadioBtn(nextPageSqlStr, radBtnData, isChecked){
var radGrpName = "rd_" + nextPageSqlStr + "_grp_name";
var radVal = radBtnData.value;
var radLbl = radBtnData.label;
// Only create radio btn contrl set if there is a 'val' prop for the radio button
if(radVal){
var radId = "rd_" + radVal + "_id";
// Create new container DIV
var rdDiv = dojo.create("div", {
id : "rd_" + radVal + "_div_id"
});
// Create the radio btn and put it into the new DIV
dojo.require("dijit.form.RadioButton");
var radioB = new dijit.form.RadioButton({
id: radId,
checked: isChecked,
value: radVal,
name: radGrpName
});
dojo.place(radioB.domNode, rdDiv, "last");
// Create the label and put it into the new DIV
if(radLbl){
var radioBlbl = dojo.create("label", {
"for": radId,
innerHTML: radLbl
});
dojo.place(radioBlbl, rdDiv, "last");
}
// Put the new DIV into the static radio btns containing DIV
dojo.place(rdDiv, dojo.byId("rdbtns_div_id"), "last");
}
}
function pushCloneOnStack() {
/// Push cloned node onto the stack
var contentDomPush = dojo.byId("mycontentdiv");
var cloned = dojo.clone(contentDomPush);
dojo.attr(cloned, "id", "mycontentdivCloned");
mainContentStack.push(cloned);
// Every push means there is a page to go back to, so enable back btn
dojo.byId("backBtn").disabled = false;
}
function popAndAssignFromStack() {
if (mainContentStack && mainContentStack.length > 0) {
// Overwrite the main content with the version popped from the stack
var contentDomPop = mainContentStack.pop();
// Clear the div
destroyAll("mycontentdiv");
dojo.attr(contentDomPop, "id", "mycontentdiv");
dojo.place(contentDomPop, dojo.byId("mycontentcontainerdiv"), "only");
// Every pop means there is a page to go forward to, so enable next btn
dojo.byId("nextBtn").disabled = false;
}
if (mainContentStack.length == 0) {
// Nothing more to pop means there is no page to go back to, so disable the back btn
dojo.byId("backBtn").disabled = true;
}
}
</script>
</head>
<body class="soria">
<div id="mycontentcontainerdiv">
<div id="mycontentdiv">
Radios Btns:
<div id="rdbtns_div_id"></div>
<br>
Radio Selected:
<div id="rdbtns_sel_div_id"></div>
</div>
</div>
<br>
<div id="btnsDiv">
<button data-dojo-type="dijit/form/Button" type="button" id="backBtn">
Back
<script type="dojo/on" data-dojo-event="click">
onBackClicked();
</script>
</button>
<button data-dojo-type="dijit/form/Button" type="button" id="nextBtn">
Next
<script type="dojo/on" data-dojo-event="click">
onNextClicked();
</script>
</button>
</div>
</body>
</html>
The problem is that you are in an odd place, you cloned the widgets DOM, but the reference to the widget in the registry is removed in your destroy(if you do a dijit.registry.toArray() you will see the radio buttons are not there). So you have the DOM aspect of the widget but none of its backend support.
What you can do is keep a copy of the DOM before the parser has parsed it. You would have to create the radiobuttons as html first, clone then run the parse command. After you do the destroy you can re-add the nonparsed html back, then run the parser again.
Here is somebody that had the same problem:
http://www.developer-corner.com/2011/06/cloning-dijit-widgets.html

Categories

Resources