MenuRef GetControl32BitValue always return 0 - menu

Hello i' need to use a pop-up menu, witch is created dynamically.
OSErr err = GetBevelButtonMenuHandle(m_pRecallAOptionalButton, &m_pRecallAMenuRef);
for (countitem)
{
String szItem (List.GetAt(i));
CFStringRef sz = ToCFStringRef(szItem);
AppendMenuItemTextWithCFString(m_pRecallAMenuRef, sz, 0, 0, 0);
}
short sCount = CountMenuItems(m_pRecallAMenuRef);
SetControl32BitMaximum(m_pRecallAOptionalButton, sCount);
This is ok, menu show the correct number of items. I set maximum value.
My problem occur when i want to get the selected item index.
For this, i use the kEventClassMenu event & kEventMenuClosed kind
case kEventClassMenu:
{
MenuRef Menu;
GetEventParameter( inEvent, kEventParamDirectObject, typeMenuRef, NULL, sizeof(Menu), NULL, &Menu );
if (Menu && (Menu == pMainForm->m_pRecallAMenuRef))
{
SInt32 nIndex = GetControl32BitMaximum(m_pRecallAOptionalButton); // return the correct items count
nIndex = GetControl32BitValue(m_pRecallAOptionalButton); // always return 0 !!!!!
}
}
Did i missed something ? is it the right event to attach ?
Many thanks for help.

You probably want to handle kEventClassCommand/kEventProcessCommand, and use the command id from the menu item.
HICommand command;
GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL,
sizeof( HICommand ), NULL, &command );
switch (command.commandID) {
case 1:
... etc ...
Note that the commandID is one of the parameters to AppendMenuItemTextWithCFString; that's how you can give each item a unique commandID as you generate the menu. commandID's are conventionally 4-char codes (like 'open' or 'save'), but there's no reason you couldn't use simple ints for your dynamically-generated commands.

Related

Distinct values in Azure Search Suggestions?

I am offloading my search feature on a relational database to Azure Search. My Products tables contains columns like serialNumber, PartNumber etc.. (there can be multiple serialNumbers with the same partNumber).
I want to create a suggestor that can autocomplete partNumbers. But in my scenario I am getting a lot of duplicates in the suggestions because the partNumber match was found in multiple entries.
How can I solve this problem ?
The Suggest API suggests documents, not queries. If you repeat the partNumber information for each serialNumber in your index and then suggest based on partNumber, you will get a result for each matching document. You can see this more clearly by including the key field in the $select parameter. Azure Search will eliminate duplicates within the same document, but not across documents. You will have to do that on the client side, or build a secondary index of partNumbers just for suggestions.
See this forum thread for a more in-depth discussion.
Also, feel free to vote on this UserVoice item to help us prioritize improvements to Suggestions.
I'm facing this problem myself. My solution does not involve a new index (this will only get messy and cost us money).
My take on this is a while-loop adding 'UserIdentity' (in your case, 'partNumber') to a filter, and re-search until my take/top-limit is met or no more suggestions exists:
public async Task<List<MachineSuggestionDTO>> SuggestMachineUser(string searchText, int take, string[] searchFields)
{
var indexClientMachine = _searchServiceClient.Indexes.GetClient(INDEX_MACHINE);
var suggestions = new List<MachineSuggestionDTO>();
var sp = new SuggestParameters
{
UseFuzzyMatching = true,
Top = 100 // Get maximum result for a chance to reduce search calls.
};
// Add searchfields if set
if (searchFields != null && searchFields.Count() != 0)
{
sp.SearchFields = searchFields;
}
// Loop until you get the desired ammount of suggestions, or if under desired ammount, the maximum.
while (suggestions.Count < take)
{
if (!await DistinctSuggestMachineUser(searchText, take, searchFields, suggestions, indexClientMachine, sp))
{
// If no more suggestions is found, we break the while-loop
break;
}
}
// Since the list might me bigger then the take, we return a narrowed list
return suggestions.Take(take).ToList();
}
private async Task<bool> DistinctSuggestMachineUser(string searchText, int take, string[] searchFields, List<MachineSuggestionDTO> suggestions, ISearchIndexClient indexClientMachine, SuggestParameters sp)
{
var response = await indexClientMachine.Documents.SuggestAsync<MachineSearchDocument>(searchText, SUGGESTION_MACHINE, sp);
if(response.Results.Count > 0){
// Fix filter if search is triggered once more
if (!string.IsNullOrEmpty(sp.Filter))
{
sp.Filter += " and ";
}
foreach (var result in response.Results.DistinctBy(r => new { r.Document.UserIdentity, r.Document.UserName, r.Document.UserCode}).Take(take))
{
var d = result.Document;
suggestions.Add(new MachineSuggestionDTO { Id = d.UserIdentity, Namn = d.UserNamn, Hkod = d.UserHkod, Intnr = d.UserIntnr });
// Add found UserIdentity to filter
sp.Filter += $"UserIdentity ne '{d.UserIdentity}' and ";
}
// Remove end of filter if it is run once more
if (sp.Filter.EndsWith(" and "))
{
sp.Filter = sp.Filter.Substring(0, sp.Filter.LastIndexOf(" and ", StringComparison.Ordinal));
}
}
// Returns false if no more suggestions is found
return response.Results.Count > 0;
}
public async Task<List<string>> SuggestionsAsync(bool highlights, bool fuzzy, string term)
{
SuggestParameters sp = new SuggestParameters()
{
UseFuzzyMatching = fuzzy,
Top = 100
};
if (highlights)
{
sp.HighlightPreTag = "<em>";
sp.HighlightPostTag = "</em>";
}
var suggestResult = await searchConfig.IndexClient.Documents.SuggestAsync(term, "mysuggestion", sp);
// Convert the suggest query results to a list that can be displayed in the client.
return suggestResult.Results.Select(x => x.Text).Distinct().Take(10).ToList();
}
After getting top 100 and using distinct it works for me.
You can use the Autocomplete API for that where does the grouping by default. However, if you need more fields together with the result, like, the partNo plus description it doesn't support it. The partNo will be distinct though.

How to get web element (id) from the element position in D3.js force graph

I am working with the D3.js force graph but I am not able to find out the element id from the element position (which I know).
I am using Leap motion. I need to simulate a mouse event (a click, a move, a drag, etc.) without a mouse. And, if I am right, in order to be able to do this, I need to find out what is the the element id from the coordinates x and y (these coordinates I know from the Leap motion pointer). So from what you wrote above, I need to find out the ('.node’).
Here is what I already tried but it did not work:
Is it possible to use non-mouse, non-touch events to interact with a D3.js graph? If so, what is the most efficient way to go about it?
So I used this function (see below), but I need to know the element id to make it work correctly:
//graph.simulate(document.getElementById("r_1"), 'dblclick', {pointerX: posX, pointerY: posY});
//here id r_1 is hardcoded, but I need to find out id from x and y coordinates.
this.simulate = function (element, eventName) {
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
var eventMatchers = {
'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
};
var defaultOptions = {
pointerX: 0,
pointerY: 0,
button: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
bubbles: true,
cancelable: true
};
var options = extend(defaultOptions, arguments[2] || {});
var oEvent, eventType = null;
for (var name in eventMatchers) {
if (eventMatchers[name].test(eventName)) {
eventType = name;
break;
}
}
if (!eventType)
throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
if (document.createEvent) {
oEvent = document.createEvent(eventType);
if (eventType == 'HTMLEvents') {
oEvent.initEvent(eventName, options.bubbles, options.cancelable);
}
else {
oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
}
element.dispatchEvent(oEvent);
}
else {
options.clientX = options.pointerX;
options.clientY = options.pointerY;
var evt = document.createEventObject();
oEvent = extend(evt, options);
element.fireEvent('on' + eventName, oEvent);
}
return element;
}
Many thanks for your help and ideas.
If you want access to the element, it's implicit in D3's iterators via this.
d3.selectAll('.node').each(function(d) {
console.log(this); // Logs the element attached to d.
});
If you really need access to the id, you can get it with selection.attr():
d3.selectAll('.node').each(function() {
console.log(d3.select(this).attr('id')); // Logs the id attribute.
});
You don't have to use each. Any of the iterators, such as attr or style, etc., have 'this' as the bound element:
d3.selectAll('.node').style('opacity', function(d) {
console.log(this);// Logs the element attached to d.
});
If you want the x and y coordinates of a node, it's part of the data:
d3.selectAll('.node').each(function(d) {
console.log(d.x, d.y); // Logs the x and y position of the datum.
});
If you really need the node attributes themselves, you can use the attr accessor.
d3.selectAll('.node').each(function(d) {
// Logs the cx and cy attributes of a node.
console.log(d3.select(this).attr('cx'), d3.select(this).attr('cy'));
});
EDIT: It looks like you need an element reference, but the only thing you know about the node in context is its position. One solution is to search through all nodes for a node with matching coordinates.
// Brute force search of all nodes.
function search(root, x, y) {
var found;
function recurse(node) {
if (node.x === x && node.y === y)
found = node;
!found && node.children && node.children.forEach(function(child) {
recurse(child);
});
}
recurse(root);
return found;
}
However this only gives you the node object, not the element itself. You will likely need to store the element references on the nodes:
// Give each node a reference to its dom element.
d3.selectAll('.node').each(function(d) {
d.element = this;
});
With that in place, you should be able to access the element and get its id.
var id, node = search(root, x, y);
if (node) {
id = node.element.getAttribute('id');
}
The brute-force search is fine for a small number of nodes, but if you're pushing a large number of nodes you might want to use D3's quadtree (example) to speed up the search.
Use d3.select('#yourElementId')
For more info check this out: https://github.com/mbostock/d3/wiki/Selections

Adding Multiple Views to a VC++ 2010 SDI using MFC

I'm trying to add multiple (actually 3 ) views to an SDI application and give the user choose witch View will be load according to his choice :
IMG
I have followed this tutorial in the official MS documentation .
So, have created three classes : CAdminView CAssistantView CBiblioView and an authentication class associated to a dialog frame .
My Questions are :
1) how to edit this three view classes (Graphically) ?
2) at first time I want to show just the authentication dialog window , how to do that ?
* I tried to change m_pMainWnd->ShowWindow(SW_SHOW);
by m_pMainWnd->ShowWindow(SW_HIDE); but no expected result
3) I expect to load the view according to parameter, this is what I added to the InitInstance funnction :
CView* pActiveView = ((CFrameWnd*) m_pMainWnd)->GetActiveView();
m_BiblioView = (CView*) new CBiblioView;
m_AdminView = (CView*) new CAdminView;
m_AssistantView = (CView*) new CAssistantView;
CDocument* pCurrentDoc = ((CFrameWnd*)m_pMainWnd)->GetActiveDocument();
// Initialize a CCreateContext to point to the active document.
// With this context, the new view is added to the document
// when the view is created in CView::OnCreate().
CCreateContext newContext;
newContext.m_pNewViewClass = NULL;
newContext.m_pNewDocTemplate = NULL;
newContext.m_pLastView = NULL;
newContext.m_pCurrentFrame = NULL;
newContext.m_pCurrentDoc = pCurrentDoc;
// The ID of the initial active view is AFX_IDW_PANE_FIRST.
// Incrementing this value by one for additional views works
// in the standard document/view case but the technique cannot
// be extended for the CSplitterWnd case.
UINT viewID = AFX_IDW_PANE_FIRST + 1;
CRect rect(0, 0, 0, 0); // Gets resized later.
// Create the new view. In this example, the view persists for
// the life of the application. The application automatically
// deletes the view when the application is closed.
m_AdminView->Create(NULL, "Fenetre Administrarteur", WS_CHILD, rect, m_pMainWnd, viewID, &newContext);
m_AssistantView->Create(NULL, "Fenetre Assistant", WS_CHILD, rect, m_pMainWnd, viewID, &newContext);
m_BiblioView->Create(NULL, "Fenetre Bibliothecaire ", WS_CHILD, rect, m_pMainWnd, viewID, &newContext);
// When a document template creates a view, the WM_INITIALUPDATE
// message is sent automatically. However, this code must
// explicitly send the message, as follows.
m_AdminView->SendMessage(WM_INITIALUPDATE, 0, 0);
m_AssistantView->SendMessage(WM_INITIALUPDATE, 0, 0);
m_BiblioView->SendMessage(WM_INITIALUPDATE, 0, 0);
and this is my switch function :
CView* CMiniProjetApp::SwitchView(int Code ) //1 : Admi / 2 : Biblio / 3 : Assistant
{
CView* pActiveView =((CFrameWnd*) m_pMainWnd)->GetActiveView();
CView* pNewView= NULL;
switch(Code){
case 1 : pNewView= m_AdminView; break;
case 2 : pNewView= m_BiblioView; break;
case 3 : pNewView= m_AssistantView; break;
}
// Exchange view window IDs so RecalcLayout() works.
#ifndef _WIN32
UINT temp = ::GetWindowWord(pActiveView->m_hWnd, GWW_ID);
::SetWindowWord(pActiveView->m_hWnd, GWW_ID, ::GetWindowWord(pNewView->m_hWnd, GWW_ID));
::SetWindowWord(pNewView->m_hWnd, GWW_ID, temp);
#else
UINT temp = ::GetWindowLong(pActiveView->m_hWnd, GWL_ID);
::SetWindowLong(pActiveView->m_hWnd, GWL_ID, ::GetWindowLong(pNewView->m_hWnd, GWL_ID));
::SetWindowLong(pNewView->m_hWnd, GWL_ID, temp);
#endif
pActiveView->ShowWindow(SW_HIDE);
pNewView->ShowWindow(SW_SHOW);
((CFrameWnd*) m_pMainWnd)->SetActiveView(pNewView);
((CFrameWnd*) m_pMainWnd)->RecalcLayout();
pNewView->Invalidate();
return pActiveView;
}
Any errors notices ??!!
*please help me !
Thanks .
Showing and Hiding the window is the correct way. But you Need to set the view as active too.
You find the required working codein this MSDN Sample VSSWAP32.
The required code to switch and hide the other views is shown in the article.

Error printing specific page range in microsoft word in c++ app

I have a strange problem where I'm trying to print a specific page range in microsoft word from a console app and I'm seeing strange results and I'm assuming it's something I did incorrectly when specifying a page range.
It appears that after I print a page range and go to get the total number of pages in the word document this number varies after I print specific ranges. Another weird thing is that this works in debug mode but not in release mode.
ex.
Word document consists of 2 pages
Print page 1-1.
Get number of pages returns 2
Print page 2-2
Get number of pages returns 1
Code is below for printing a range of pages:
int CWordComm::PrintAndCloseActiveDocument(int iNumOfCopies, short nTray, int pageNumber)
{
// Convenient values declared as ColeVariants.
COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
_Document oActiveDoc = m_oWord.GetActiveDocument();
if(!this->m_szOutputFilename.IsEmpty())
{
//If we are outputting the document to a file then we need to print a single page at a time
//This is because of a limitation on the ikonprinter/requisition printer side that can only handle
//one page at a time
// Print out to file
CString szCurrentPage, szPrintRange;
szCurrentPage.Format("%d", pageNumber);
szPrintRange.Format("%d", PRINT_FROM_TO); //PRINT_FROM_TO is #define PRINT_FROM_TO 3
COleVariant printRange(szPrintRange, VT_BSTR);
COleVariant currentPage(szCurrentPage, VT_BSTR);
sprintf(m_szLogMessage, "Printing page %d of requisition", pageNumber);
LogMessage(m_szLogMessage);
oActiveDoc.PrintOut(covFalse, // Background.
covOptional, // Append.
printRange, // Range.
COleVariant(szFileName,VT_BSTR), // OutputFileName.
currentPage, // From.
currentPage, // To.
covOptional, // Item.
COleVariant((long)1), // Copies.
covOptional, // Pages.
covOptional, // PageType.
covTrue, // PrintToFile.
covOptional, // Collate.
covOptional, // ActivePrinterMacGX.
covOptional // ManualDuplexPrint.
);
}
else
{
// Print out to file
oActiveDoc.PrintOut(covFalse, // Background.
covOptional, // Append.
covOptional, // Range.
COleVariant(szFileName,VT_BSTR), // OutputFileName.
covOptional, // From.
covOptional, // To.
covOptional, // Item.
COleVariant((long)1), // Copies.
covOptional, // Pages.
covOptional, // PageType.
covTrue, // PrintToFile.
covOptional, // Collate.
covOptional, // ActivePrinterMacGX.
covOptional // ManualDuplexPrint.
);
}
//Get the number of pages in the word document
iNumPages=GetActiveDocPageCount();
//omitted code
}
Get pages method
int CWordComm::GetActiveDocPageCount()
{
try
{
_Document oActiveDoc;
//Get the Active Document
oActiveDoc = m_oWord.GetActiveDocument();
//Get the BuiltinDocumentProperties collection for the
//document
LPDISPATCH lpdispProps;
lpdispProps = oActiveDoc.GetBuiltInDocumentProperties();
//Get the requested Item from the BuiltinDocumentProperties
//collection
//NOTE: The DISPID of the "Item" property of a
// DocumentProperties object is 0x0
VARIANT vResult;
DISPPARAMS dpItem;
VARIANT vArgs[1];
vArgs[0].vt = VT_BSTR;
//property name for the number of pages in the active document
_bstr_t btVal("Number of pages");
vArgs[0].bstrVal = btVal;
dpItem.cArgs=1;
dpItem.cNamedArgs=0;
dpItem.rgvarg = vArgs;
HRESULT hr = lpdispProps->Invoke(0x0, IID_NULL,
LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
&dpItem, &vResult, NULL, NULL);
//Get the Value property of the BuiltinDocumentProperty
//NOTE: The DISPID of the "Value" property of a
// DocumentProperty object is 0x0
DISPPARAMS dpNoArgs = {NULL, NULL, 0, 0};
LPDISPATCH lpdispProp;
lpdispProp = vResult.pdispVal;
hr = lpdispProp->Invoke(0x0, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYGET, &dpNoArgs, &vResult,
NULL, NULL);
CString sPropValue = "";
switch (vResult.vt)
{
case VT_BSTR:
sPropValue = vResult.bstrVal;
break;
case VT_I4:
sPropValue.Format("%d",vResult.lVal);
break;
case VT_DATE:
{
COleDateTime dt (vResult);
sPropValue = dt.Format(0, LANG_USER_DEFAULT);
break;
}
default:
// sPropValue = "<Information for the property you selected is not available>";
sPropValue = "-4";
break;
}
//Release the no longer needed IDispatch pointers
lpdispProp->Release();
lpdispProps->Release();
return atoi(sPropValue);
}
catch(...)
{
return FUNC_ERROR;
}
}
Question
Is there something obvious I am doing wrong here? Should I be interfacing with word in a different way if I wish to print a range of pages?
If it works fine in the debug mode, I suggest you write the values ( eg No of pages, page being printed etc ) to a text file. Compare the debug log output , with the release log output. Here's a link which might help you. The link is not in C++, but might guide you in the right way.
It turns out this is some sort of timing issue. I put a 500ms sleep after the printing of the document and before the calculation of the number of pages and I'm now consistently getting the correct results.
When I was debugging it was essentially doing this same thing.

Preventing tab to cycle through address bar

I realize this is probably an accessibility issue that may best be left alone, but I'd like to figure out if it possible to prevent the tab from visiting the address bar in the tabbing cycle.
My application has another method of cycling through input areas, but many new users instinctively try to use the tab, and it doesn't work as expected.
Here's a generic jquery implementation where you don't have to find the max tab index. Note that this code will also work if you add or remove elements in your DOM.
$('body').on('keydown', function (e) {
var jqTarget = $(e.target);
if (e.keyCode == 9) {
var jqVisibleInputs = $(':input:visible');
var jqFirst = jqVisibleInputs.first();
var jqLast = jqVisibleInputs.last();
if (!e.shiftKey && jqTarget.is(jqLast)) {
e.preventDefault();
jqFirst.focus();
} else if (e.shiftKey && jqTarget.is(jqFirst)) {
e.preventDefault();
jqLast.focus();
}
}
});
However, you should note that the code above will work only with visible inputs. Some elements may become the document's activeElement even if they're not input so if it's your case, you should consider adding them to the $(':input:visible') selector.
I didn't add code to scroll to the focus element as this may not be the wanted behavior for everyone... if you need it, just add it after the call to focus()
You can control the tabbing order (and which elements should be able to get focus at all) with the global tabindex attribute.
However, you can't prevent users to tab into another context not under control of the page (e.g. the browser's address bar) with this attribute. (It might be possible in combination with JavaScript, though.)
For such a (evil!) use case, you'd have to look into keyboard traps.
WCAG 2.0 has the guideline: 2.1.2 No Keyboard Trap. In Understanding SC 2.1.2 you can find "Techniques and Failures" for this guideline:
F10: Failure of Success Criterion 2.1.2 and Conformance Requirement 5 due to combining multiple content formats in a way that traps users inside one format type
FLASH17: Providing keyboard access to a Flash object and avoiding a keyboard trap
G21: Ensuring that users are not trapped in content
So maybe you get some ideas by that how such a trap would be possible.
I used to add two tiny, invisible elements on tabindex 1 and on the last tabindex. Add a onFocus for these two: The element with tabindex 1 should focus the last real element, the one with the max tabindex should focus the first real element. Make sure that you focus the first real element on Dom:loaded.
You could use Javascript and capture the "keydown" event on the element with the highest "tabindex". If the user presses the "TAB" key (event.keyCode==9) without the "Shift" key (event.shiftKey == false) then simply set the focus on the element with the lowest tabindex.
You would then also need to do the same thing in reverse for the element with the lowest tabindex. Capture the "keydown" event for this element. If the user presses the "TAB" key (event.keyCode==9) WITH the "Shift" key (event.shiftKey == true) then set the focus on the element with the highest tabindex.
This would effectively prevent the address bar from ever being focused using the TAB key. I am using this technique in my current project.
Dont forget to cancel the keydown event if the proper key-combination is pressed! With JQuery it's "event.preventDefault()". In standard Javascript, I believe you simply "return false".
Here's a JQuery-laden snippet I'm using...
$('#dos-area [tabindex=' + maxTabIndex + ']').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('#dos-area [tabindex=1]').focus();
}
});
$('#dos-area [tabindex=1]').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == true) {
e.preventDefault();
$('#dos-area [tabindex=' + maxTabIndex + ']').focus();
}
});
Also keep in mind that setting tabindex=0 has undesirable results on the order in which things are focused. I always remember (for my purposes) that tabindex is a 1-based index.
Hi i have an easy solution. just place an empty span on the end of the page. Give it an id and tabindex = 0, give this span an onfocus event, when triggered let your focus jump to the first element on your page you want to cycle trough. This way you won't lose focus on the document, because if you do your events don't work anymore.
I used m-albert solution and it works. But in my case I do not control the tabindex properties. My intention is set the focus on a toolbar at the top of the page (first control) when user leaves the last control on the page.
$(':input:visible').last().on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 500);
$(':input:visible', context).first().focus();
}
});
Where context can be any Jquery object, selector, or even document, or you can omit it.
The scrolling animation, of course, is optional.
Not sure if this is still a issue, but I implemented my own solution that does not use jQuery, can be used in the case when all the elements have tabindex="0", and when the DOM is subject to change. I added an extra argument for a context if you want to limit the tabcycling to a specific element containing the tabindex elements.
Some brief notes on the arguments:
min must be less than or equal to max, and contextSelector is an optional string that if used should be a valid selector. If contextSelector is an invalid selector or a selector that doesn't match with any elements, then the document object is used as the context.
function PreventAddressBarTabCyle(min, max, contextSelector) {
if( isNaN(min) ) throw new Error('Invalid argument: first argument needs to be a number type.')
if( isNaN(max) ) throw new Error('Invalid argument: second argument needs to be a number type.')
if( max < min ) throw new Error('Invalid arguments: first argument needs to be less than or equal to the second argument.')
min = min |0;
max = max |0;
var isDocumentContext = typeof(contextSelector) != 'string' || contextSelector == '';
if( min == max ) {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindexElements = context.querySelectorAll('[tabindex]');
if( tabindexElements.length <= 0 ) return;
var targetIndex = -1;
for(var i = 0; i < tabindexElements.length; i++) {
if( e.target == tabindexElements[i] ) {
targetIndex = i;
break;
}
}
// Check if tabbing backward and reached first element
if( e.shiftKey == true && targetIndex == 0 ) {
e.preventDefault();
tabindexElements[tabindexElements.length-1].focus();
}
// Check if tabbing forward and reached last element
if( e.shiftKey == false && targetIndex == tabindexElements.length-1 ) {
e.preventDefault();
tabindexElements[0].focus();
}
};
} else {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindex = parseInt(e.target.getAttribute('tabindex'));
if( isNaN(tabindex) ) return;
// Check if tabbing backward and reached first element
if (e.shiftKey == true && tabindex == min) {
e.preventDefault();
context.querySelector('[tabindex="' + max + '"]').focus();
}
// Check if tabbing forward and reached last element
else if (e.shiftKey == false && tabindex == max) {
e.preventDefault();
context.querySelector('[tabindex="' + min + '"]').focus();
}
};
}
document.body.addEventListener('keydown', tabCycleListener, true);
}
More notes:
If min is equal to max, then tab cycling will occur naturally until the last element in the context is reached. If min is strictly less than max, then tabbing will cycle naturally until either the min or the max is reached. If tabbing backwards and the min is reached, or tabbing forward and the max is reached, then the tabbing will cycle to the min element or max element respectively.
Example usage:
// For all tabindex elements inside the document
PreventAddressBarTabCyle(0,0);
// Same as above
PreventAddressBarTabCyle(1,1);
// NOTE: if min == max, the tabindex value doesn't matter
// it matches all elements with the tabindex attribute
// For all tabindex elements between 1 and 15
PreventAddressBarTabCyle(1,15);
// For tabindex elements between 1 and 15 inside
// the first element that matches the selector: .some-form
PreventAddressBarTabCyle(1,15, '.some-form');
// For all tabindex elements inside the element
// that matches the selector: .some-form2
PreventAddressBarTabCyle(1,1, '.some-form2');
Salinan solution worked for me
Put this in the start of your html page:
<span tabindex="0" id="prevent-outside-tab"></span>
and this at the end of your html page.:
<span tabindex="0" onfocus="foucsFirstElement()"></span>
foucsFirstElement() :
foucsFirstElement() {
document.getElementById("prevent-outside-tab").focus();
},

Resources