How to bind an event to Tabbing Off an element? - javascript

I'm using the following for a dropdown:
/* recurse through dropdown menus */
$('.dropdown').each(function() {
/* track elements: menu, parent */
var dropdown = $(this);
var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent();
/* function that shows THIS menu */
var showMenu = function() {
hideMenu();
showingDropdown = dropdown.addClass('dropdown-active');
showingMenu = menu.show();
showingParent = parent;
};
/* function to show menu when clicked */
dropdown.bind('click',function(e) {
if(e) e.stopPropagation();
if(e) e.preventDefault();
showMenu();
});
/* function to show menu when someone tabs to the box */
dropdown.bind('focus',function() {
showMenu();
});
});
/* hide when clicked outside */
$(document.body).bind('click',function(e) {
if(showingParent) {
var parentElement = showingParent[0];
if(!$.contains(parentElement,e.target) || !parentElement == e.target) {
hideMenu();
}
}
});
Notice:
$(document.body).bind('click',function(e) {
The problem is that the dropdown opens on click or when you tab to it. But it only closes on click, not when you tab out.
How can I bind an event to mean "tabbing out" ,losing focus, so the dropdown closes?
Thanks

You could trigger a click outside when you press the tab key. Like this:
$('#your_dropdown').bind('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) { //If it's the tab key
$("body").click(); //Force a click outside the dropdown, so it forces a close
}
});
Hope this helps. Cheers

Try the blur event, which will be triggered when the control loses focus (i.e., when the user clicks outside the control or uses the keyboard to tab to the next control).
Put something like this just after your existing focus binding:
dropdown.bind('blur',function() {
// whatever tests you want
hideMenu();
});
(You shouldn't then need the separate click binding that you're currently using to hide the menu.)
P.S. You might also consider focusout, which is similar to blur except that it bubbles.

Seems like you're looking for the onblur event?

Related

Click outside menu to close it

Here's my function,
$(document).ready(function () {
$('.a').click(function () {
var here = $(this).next('.b');
if (here.is(":visible")) {
here.hide();
} else {
here.show();
}
return false;
});
});
So, whenever I click the button it opens a small tab on same webpage & whenever I click it again it closes it. But once I open the tab I can't close it by just clicking somewhere on webpage apart from tab. I have to click the button again to close it.
How can I close tab just by clicking somewhere on webpage also by on the button?
I end up searching for this on almost every project, so I made this plugin:
jQuery.fn.clickOutside = function(callback){
var $me = this;
$(document).mouseup(function(e) {
if ( !$me.is(e.target) && $me.has(e.target).length === 0 ) {
callback.apply($me);
}
});
};
It takes a callback function and passes your original selector, so you can do this:
$('[selector]').clickOutside(function(){
$(this).removeClass('active'); // or `$(this).hide()`, if you must
});
Nice, chainable, elegant code.
On document click, the closest helps to check whether the tab has been clicked or not:
$(document).click(function (e) {
if($('.b').is(':visible')&&!$(e.target).closest('.b').length){
$('.b').hide();
}
});
You want to check for a click on the body :
$("body").click(function(e) {
if(e.target.id !== 'menu'){
$("#menu").hide();
}
});
menu would be the id of the menu.
If the body is clicked and the id of the div clicked doesn't equal that of the menu, then it closes.
Check this implementation
jQuery(document).ready(function() {
$(document).on('click','body, #btn',function(ev){
ev.stopPropagation()
if(ev.target.id== "btn"){
if($('#modal').is(':visible')) {
$('#modal').fadeOut();
} else{
$('#modal').fadeIn();
}
} else {
$('#modal').fadeOut();
}
});
});
html, body {
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">
Click Me!
</button>
<div id="modal" style="background-color:red;display:none;">
BLA BLA BLA
</div>
To check if the clicked element is outside of a given container, i.e. a menu, we can simply check if the event target is a child of the container. Using JQuery -
$('body').click(function(e) {
if ( 0 === $(e.target).parents('#container-id').length ) {
/// clicked outside -> do action
}
})
you have to add a click listener to the parent element, like here:
$('.parent-div').click(function() {
//Hide the menus if visible
});
Also because click events bubbled up from child to the parent,
you can exclude the click on the child element to get bubbled up and count as the parent click too. you can achieve this like below:
//disable click event on child element
$('.child-div').click(function(event){
event.stopPropagation();
});

Clickoutside event doen't work on iframe

It's a rich-text editor,there is a div show the content users typed in, just like this:
<div class=‘content’>
<iframe data-role=text-editable.></iframe>
</div>
When i click a icon who's used to call the color panel,the panel will show.And i wish when i click outside the panel,it will be hide.so my code is:
var color_panel = $('.color-panel');
color_panel.on("clickoutside", function (e) {
var t = $(e.target);
if ($.contains(color_panel[0], t[0]))
return;
color_panel.hide();
})
It works well when i click outside the panel will disappear except i click the iframe.when i click the ifame,nothing happens,the panel is still shown,
Help......i want to know the reason .please...is the ifame not the dom element outside the panel?
You can listen for outside clicks by listening for clicks on the body element of the webpage (so, clicking on anything element) and then you can exclude your .color_panel from this event by making another event that says "when I get clicked on, ignore any other clicks". The effect will be exactly what you want, that you can listen for outside clicks:
var panelOpen = false;
$('body').click(function(event) {
if (panelOpen) {
panelOpen = false;
color_panel.hide();
}
});
$('.color_panel').click(function(event) {
panelOpen = true;
//callYourMethodToShowThePanelHere();
e.preventDefault(); // these methods will stop the body click event
e.stopPropagation();
return false;
});

.click() event not working for mobile in Javascript

I am having a problem with my code, I have a hidden a href link that the href value is added once a click is detected in a image and the link is pass as a value the the hidden href. So once it clicks on the image in Javascript I am making the manually .click() to the hidden href tag but it is not working in mobiles. My code is below:
processGridClick : function(obj){
var objIndex = obj.getAttribute('data-item-number');
var docType = obj.getAttribute('data-doc-type');
if(obj.className.indexOf('single') > -1){
var documentURL = "";
var documentsJsonRoot = DocumentsMgr.documentationData.documents[objIndex];
if(docType == 'reportsList'){
documentURL = documentsJsonRoot.reportsList[0].url;
}else if(docType == 'attachmentList'){
documentURL = documentsJsonRoot.attachmentList[0].url;
}
dojo.attr('linkDocumentsSingle', "href", documentURL);
document.getElementById('linkDocumentsSingle').click();
}
}
The view is a table that is generated in base of a JSON object and it can have more than one row, the value of the href is passed in base of the image that they clicked. This works good for desktop but in mobile the .click is not working, I even tried to add manually the touchstart event to all the clickable elements with the code below but stills not working.
**(function(window){
// check for touch
if (Modernizr.touch) {
// run the forEach on each figure element
[].slice.call(document.querySelectorAll("figure")).forEach(function(el,i){
// check if the user moves a finger
var fingerMove = false;
el.addEventListener("touchmove",function(e){
e.stopPropagation();
fingerMove = true;
});
// always reset fingerMove to false on touch start
el.addEventListener("touchstart",function(e){
e.stopPropagation();
fingerMove = false;
});
// add hover class if figure touchend and fingerMove is false
el.addEventListener("touchend",function(e){
e.stopPropagation();
if (fingerMove == false) {
classie.toggle(el,"hover");
}
});
});
}
})(window);**
Will this work for mobile? Try simulating a mouse click...?
var ele = document.getElementById('linkDocumentsSingle');
ele.dispatchEvent(new MouseEvent('mousedown'));
ele.dispatchEvent(new MouseEvent('mouseup'));
Try to use this
In i phones there is a click event only for anchor tag or buttons. So for image, div or span you have to use tap event.
// listen for a touchstart event
$('img').on('touchstart.tap',function (e) {
// listen for a touchend event
$(e.target).one('touchend.tap',function() {
$(e.target).trigger('tap');
});
// cancel it in 150ms
setTimeout(function () {
$(e.target).off('touchend.tap');
},150);
});
This will trigger a tap event if a touchend follows a touchstart within 150ms (which you can adjust, of course). You could try using this in lieu of including jQuery mobile if a tap event is all you're after.
Note: For this i have examined you have included bootstrap js library

How to trigger focusout event on a ul element?

I have a plugin that changes the look of select html tag on all browser.
I'm trying to make the new styled set of elements behave like a normal select tag. I'm almost there, but I only need to figure one thing out and that's how to hide a ul on focus out.
First off, here is a demo of the new select element (not in English, but you can find it easily ^^) :
http://mahersalam.co.cc/projects/n-beta/
If you click the toggle button of the select element, and then click away, the ul element that has the options won't disappear. That's because I can't fire a focusout event on that ul.
Here is the code that controls how the events are handled:
// Make a div which will be used offline and then inserted to the DOM
$namodgSelect = $('<div class="namodg-select"></div>');
/* other stuff ... */
$namodgSelect // Handle all needed events from the wrapper
.delegate('a', 'click focus blur', function(e) {
// Type of the event
var type = e.type,
// Declare other vars
id,
$this;
e.preventDefault(); // Stop default action
// Make an id ot the element using it's tag name and it's class name
// Note: Because we add a class on the active toggler, it's easier to remove it from here and the logic will still work
id = e.target.tagName.toLowerCase() + '.' + e.target.className.replace(' toggler-active', '');
switch (id) {
case 'p.selected': case 'div.toggle-button':
// Only accept 'click' on p and div
if ( type != 'click') {
return;
}
// Show and hide the options holder
if ( $optionsHolder.data('hidden') ) {
$selectElem.focus();
// This needs to run fast to give feedback to the user
$toggler.addClass('toggler-active').data('active', true);
// Show the options div
$optionsHolder.stop(true, true).slideDown('fast', function() {
// Sometimes fast clicking makes the toggler deavtive, so show it in that case
if ( ! $toggler.data('active') ) {
$toggler.addClass('toggler-active').data('active', true);
}
}).data('hidden', false);
} else {
$selectElem.blur();
// Hide the options div
$optionsHolder.stop(true, true).slideUp(function() {
// Only hide the toggler if it's active
if ( $toggler.data('active') ) {
$toggler.removeClass('toggler-active').data('active', false);
}
}).data('hidden', true);
}
break;
case 'a.toggler':
switch (type) {
case 'focusin':
$selectElem.focus();
break;
case 'focusout':
// Only blur when the options div is deactive
if ( $optionsHolder.data('hidden') ) {
$selectElem.blur();
}
break;
case 'click':
$selectedHolder.click();
$selectElem.focus();
}
break;
case 'a.option':
// Stop accept click events
if ( type != 'click') {
return;
}
// cache this element
$this = $(this);
// Change the value of the selected option and trigger a change event
$selectedOption.val( $this.data('value') ).change();
// Change the text of the fake select and trigger a click on it
$selectedHolder.text( $this.text() ).click();
break;
}
})
The whole code can be seen from the demo. As you can see, I already use the focusout event on the toggler and the options, so I can't hide the ul when that happens (that will disable the tab functionality).
If anyone can help me with this , it will be appreciated. Thanks.
Try out the jQuery outside events plugin
Will let you do something like:
$(this).bind( "clickoutside", function(event){
$(this).hide();
});
I was able to hide the options panel using this code:
$(document).click(function() {
if ( $optionsHolder.data('hidden') || $optionsHolder.is(':animated') ) {
return;
}
$selectedHolder.click();
})
This works because focusing on another input is like a click on the document.

How to get Javascript event to fire only when the background is clicked (and not other elements)?

I'm trying to write a web app which replaces the context menu (right-click menu) with my own customized ones. I want it so that when the user clicks on a table row, they get one certain context menu and when they click on the background of the page, they get a different one.
I have already written the menus and gotten them working. The problem comes in when trying to figure out how to get the background's menu to show ONLY when clicking on the background and how to get the table row's menu to show when that is clicked.
I tried using document.body.oncontextmenu for the body and and setting the oncontextmenu function for each table row, but the body's oncontextmenu function overrides the row's so I get the wrong menu. The menu for the table rows DOES work if I stop using the body's menu, so that's not the issue.
I could be using the wrong events, so is there a different event for just the background (and not the elements on top of the background)? Or a way to "prioritize" the events so the table row's function takes precedence?
This is how the code looks:
var tableMenu;
var bodyMenu;
window.onload = function()
{
bodyMenu = new rightClickMenu("bodyMenu");
document.body.oncontextmenu = function() { bodyMenu.show(); tableMenu.hide(); }
bodyMenu.add("Add Entry", function()
{
alert("ADD");
});
tableMenu = new rightClickMenu("tableMenu", "tblSims");
simRows = getElementsByClassName("trSimRow");
for (var i in simRows)
simRows[i].oncontextmenu = function() { tableMenu.show(this.id.substring(2)); bodyMenu.hide(); }
tableMenu.add("Delete Entry", function(mac)
{
alert("DELETE");
});
document.body.onclick = function()
{
bodyMenu.hide();
tableMenu.hide();
};
}
You can capture the target element, e.g.:
$('*').click(function(e) {
alert(e.target);
alert(e.target.tagName);
if(e.target.tagName == 'html') {
// show background menu
}
});
You have to work with the Javascript Event Propagation model. What happens is that your click event is automatically passed down the layers of objects on a page that have been registered as event listeners, unless you explicitly tell it to stop, try something like this:
function setupClickHandlers()
{
document.getElementsByTagName('body')[0].onclick = doBodyMenu;
document.getElementById('tableID').onclick = doTableMenu;
}
function doBodyMenu()
{
//do whatever it does
}
function doTableMenu(e)
{
//do whatever it does
//stop the event propagating to the body element
var evt = e ? e : window.event;
if (evt.stopPropagation) {evt.stopPropagation();}
else {evt.cancelBubble=true;}
return false;
}
This should deal with the way each browser handles events.
$( document ).ready(function() {
var childClicked = false;
// myContainer is the nearest container div to the clickable elements
$("#myContainer").children().click(function(e) {
console.log('in element');
childClicked = true;
});
$("#myContainer").click(function(e){
if(!childClicked) {
console.log('in background');
e.preventDefault();
e.stopPropagation();
}
childClicked = false;
});
});
#myContainer {
width:200px;
height:200px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myContainer" style="">
link
<div style="width:50px;height:50px;background-color: white;">
another link
</div>
</div>

Categories