Toggle focus to follow toggleClass - javascript

I'm doing a simple show/hide on a search form that uses jQuery's toggleClass() and CSS to show and hide the form. That's easy enough, something like:
$('#site-search-toggle').click(function(e){
$('#site-search').toggleClass('search-open');
e.preventDefault()
});
What I'd like to do but am having a hard time figuring out is to put focus on the search input when the form is shown and remove the focus from the search input when the form is hidden.
It's easy to add focus:
$('#site-search-toggle').click(function(e){
$('#site-search').toggleClass('search-open');
$('#site-search input[type="search"]').focus();
e.preventDefault()
});
But I'm stuck at how to remove it when $('#site-search-toggle') is clicked again to hide the form.

Just found this thread as I've been banging my head against this problem for a while now.
I've found a very simple way to do this, and essentially all you need to do is provide a click handler. When the element is clicked, you toggle the class which controls the 'focused' state, but you also programatically focus the element:
document.getElementById('myelement').addEventListener('click', function() {
this.classList.toggle('focus'); // or whatever...
this.focus();
});
You will need to give the element some sort of 'tabindex' value, probably 0 or -1.
And then, you provide a 'blur' handler, which just removes the 'focus' class whenver the user navigates away from the element.
document.getElementById('myelement').addEventListener('blur', function() {
this.classList.remove('focus');
return false;
});
Works like a dream!
I'm sorry that this is not a jQuery answer, but it should be easy enough to adapt - I just don't use it...
Danny

OK I figured this one out, or at least I found a way to do what I need to do. I added a second class, search-closed, toggled both classes, then used each class to focus or blur the field, something like this:
$('#site-search').addClass('search-closed');
$('.site-search__toggle').click(function(e){
// toggle both classes
$('#site-search').toggleClass('search-open search-closed');
// set focus when form is visible, .search-open
// use setTimeout to make sure the cursor actually gets in there
// don't know why, but it works
setTimeout (function(){
$('#site-search.search-open .site-search__input').focus();
}, 20);
// blur when the form is not visible, .search-closed
$('#site-search.search-closed .site-search__input').blur();
});

Try this:
$('#site-search-toggle').click(function(e){
$('#site-search').toggleClass('search-open');
if ($('#site-search').hasClass('search-open')) {
$('#site-search input[type="search"]').focus();
} else {
$('#site-search input[type="search"]').blur();
}
e.preventDefault();
});

Related

How to use javascript to select (a) child(ren) element(s) of a hovered element?

assuming I have a (very large) div tag and inside the div tag I have a (normal size) button, now I want to be able to create a shortcut that if a user is hovering over the div tag, they can press return key to click the button.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div').hover(function(){
$('this button').click();
});
}
});
This is how I imagine it might look like in jQuery (didn't work obviously). I am open to suggestions. jQuery solutions are fine, plain javascript solutions are even better.
It's actually pretty easy.
$(window).keypress(function(e){
if (e.keyCode == xxx) {
$('div:hover button').click();
}
});
Don't use .hover() or .on('hover') because they are simply not selectors.
You can use .is(":hover") within your keypress handler to determine if the proper div is being hovered:
$(window).keypress(function(){
if($("#target").is(":hover")){
alert("pressed!");
}
});
http://jsfiddle.net/y7joukzw/2/
(NOTE: Make sure you click within the "result" frame to ensure it is the active frame when testing the jsfiddle)
Rather than checking for hover on every keypress, you're better off reversing the order of event checking so that you only incur the keypress overhead while the user is hovering. Something like:
function checkKeypress(e) {
// Check keypress and perhaps do something
}
$('div').hover(
function(){
$(window).keypress(checkKeypress);
},
function() {
$(window).off('keypress', checkKeypress);
}
);

Can anyone think of a better way of stopping a user from clicking on anything?

Currenlty when a page is posting back or something else is going on I display a big grey div over the top of the whole page so that the user can't click the same button multiple times. This works fine 99% of the time, the other 1% is on certain mobile devices where the user can scroll/zoom away from the div.
Instead of trying to perfect the CSS so that it works correctly (this will be an on going battle with new devices) I've decided to just stop the user from being able to click anything. Something like $('a').click(function(e){e.preventDefault();}); would stop people from clicking anchor tags and navigating to the link but it wouldn't stop an onclick event in the link from firing.
I want to try to avoid changing the page too radically (like removing every onclick attribute) since the page will eventually have to be changed back to its original state. What I would like to do is intercept clicks before the onclick event is executed but I don't think that this is possible. What I do instead is hide the clicked element on mouse down and show it on mouseup of the document, this stops the click event firing but doesn't look very nice. Can anyone think of a better solution? If not then will this work on every device/browser?
var catchClickHandler = function(){
var $this = $(this);
$this.attr('data-orig-display', $this.css('display'));
$this.css({display:'none'});
};
var resetClickedElems = function(){
$('[data-orig-display]').each(function(){
$(this).css({display:$(this).attr('data-orig-display')}).removeAttr('data-orig-display');
});
};
$('#btn').click(function(){
$('a,input').on('mousedown',catchClickHandler);
$(document).on('mouseup', resetClickedElems);
setTimeout(function(){
$('a,input').off('mousedown',catchClickHandler);
$(document).off('mouseup', resetClickedElems);
}, 5000);
});
JSFiddle: http://jsfiddle.net/d4wzK/2/
You could use the jQuery BlockUI Plugin
http://www.malsup.com/jquery/block/
You can do something like this to prevent all actions of the anchor tags:
jQuery('#btn').click(function(){
jQuery('a').each(function() {
jQuery(this).attr('stopClick', jQuery(this).attr('onclick'))
.removeAttr('onclick')
.click(function(e) {
e.preventDefault();
});
});
});
That renames the onclick to stopclick if you need to revert later and also stops the default behavior of following the href.
document.addListener('click',function(e){e.preventDefault()})
Modified-
Its your duty to remove the click event from the document after you are done accomplishing with your task.
Eg -
function prevent(e){
e.preventDefault()
}
//add
document.addListener('click',prevent)
//remove
document.removeListener('click',prevent)

Disable doubleclick event for an element in Opera

Is there a way to disable (with CSS, JS or jQuery) double-click for a given element?
The problem with Opera is that it displays a menu when I click on an element too fast. Note that I know how to disable this for me. I'd like to be able to disable this for all user that use the script.
The buttons in question are "next"/"previous" buttons and I use input type image for them, but the same happens with "a".
It turended out I need this:
/**
Disable text selection by Chris Barr, of chris-barr.com
*/
$.fn.disableTextSelect = function() {
return this.each(function(){
if($.browser.mozilla){//Firefox
$(this).css('MozUserSelect','none');
}else if($.browser.msie){//IE
$(this).bind('selectstart',function(){return false;});
}else{//Opera, etc.
$(this).mousedown(function(){return false;});
}
});
}
And then I could disable text selection on my button elements like this:
$(function(){ $('input[type=image]').disableTextSelect(); });
And now I can click buttons fast as hell and all works fine :-).
You cannot have a click and dblclick event handler attached on the same element because when you dblclick both the events are going to be triggered. In order to make it work there are few work arounds.
This might help you
Need to cancel click/mouseup events when double-click event detected
Looking at your problem there is a simple solution. In the click event handler once it is clicked set a disabled attribute or some class name(disabled). In the handler before exectuing your code checck for this attribute or class name. If it exists then dont do anything. After sometime remove this attribtue or class name. Try this
$("selector").click(function(){
var $this = $(this);
if(!$this.hasClass("disabled")){
//Do you stuff here
$this.addClass("disabled");
setTimeout(function(){
$this.removeClass("disabled");
}, 200);
}
});
JavaScript would do that for you.
DOMElement.ondblclick = (function () {return false;})();

Closing form on "blur" -- Is there a better way?

So, i'm trying to close a form on blur, e.g. Facebook comments. The issue is, I had a:
$(window).click(function(){ $('.comment_form').hide(); });
$('.comment_form').click(function(){ return false; });
Which worked fine, however, by adding that return false, it cancels out the submit button when clicked when i actually went to make it live.
I thought this would work logically instead:
$('*:not(.comment_form,.comment_form *)').click(function(eve)
{
$('.comment_form').hide();
});
But, unfortunatly, it doesn't and i assume it's because when i click on, let's say, .comment_form i actually am clicking on body, div, div... etc so it actually hides it multiple times.
My work around was finally
$('*').click(function(eve)
{
if(!$(eve.target).is('.comment_form,.comment_form *'))
{
$('.comment_form').hide();
}
});
However, i'm not so sure i like this and this is why im asking. This is going to fire this click event every single click.
Does anyone have any suggestions?
Your solution is on the right track, but it might be saner to attach the event to document, instead of all elements (*):
$(document).click(function(eve) {
if (!$(eve.target).is('.comment_form, .comment_form *')) {
$('.comment_form').hide();
}
});

Using jQuery to test if an input has focus

On the front page of a site I am building, several <div>s use the CSS :hover pseudo-class to add a border when the mouse is over them. One of the <div>s contains a <form> which, using jQuery, will keep the border if an input within it has focus. This works perfectly except that IE6 does not support :hover on any elements other than <a>s. So, for this browser only we are using jQuery to mimic CSS :hover using the $(#element).hover() method. The only problem is, now that jQuery handles both the form focus() and hover(), when an input has focus then the user moves the mouse in and out, the border goes away.
I was thinking we could use some kind of conditional to stop this behavior. For instance, if we tested on mouse out if any of the inputs had focus, we could stop the border from going away. AFAIK, there is no :focus selector in jQuery, so I'm not sure how to make this happen. Any ideas?
jQuery 1.6+
jQuery added a :focus selector so we no longer need to add it ourselves. Just use $("..").is(":focus")
jQuery 1.5 and below
Edit: As times change, we find better methods for testing focus, the new favorite is this gist from Ben Alman:
jQuery.expr[':'].focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
Quoted from Mathias Bynens here:
Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.
You're defining a new selector. See Plugins/Authoring. Then you can do:
if ($("...").is(":focus")) {
...
}
or:
$("input:focus").doStuff();
Any jQuery
If you just want to figure out which element has focus, you can use
$(document.activeElement)
If you aren't sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing:
(function ( $ ) {
var filters = $.expr[":"];
if ( !filters.focus ) {
filters.focus = function( elem ) {
return elem === document.activeElement && ( elem.type || elem.href );
};
}
})( jQuery );
CSS:
.focus {
border-color:red;
}
JQuery:
$(document).ready(function() {
$('input').blur(function() {
$('input').removeClass("focus");
})
.focus(function() {
$(this).addClass("focus")
});
});
Here’s a more robust answer than the currently accepted one:
jQuery.expr[':'].focus = function(elem) {
return elem === document.activeElement && (elem.type || elem.href);
};
Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.
(Taken from this gist by Ben Alman.)
April 2015 Update
Since this question has been around a while, and some new conventions have come into play, I feel that I should mention the .live method has been depreciated.
In its place, the .on method has now been introduced.
Their documentation is quite useful in explaining how it works;
The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object. As of jQuery 1.7, the .on() method
provides all functionality required for attaching event handlers. For
help in converting from older jQuery event methods, see .bind(),
.delegate(), and .live().
So, in order for you to target the 'input focused' event, you can use this in a script. Something like:
$('input').on("focus", function(){
//do some stuff
});
This is quite robust and even allows you to use the TAB key as well.
I'm not entirely sure what you're after but this sounds like it can be achieved by storing the state of the input elements (or the div?) as a variable:
$('div').each(function(){
var childInputHasFocus = false;
$(this).hover(function(){
if (childInputHasFocus) {
// do something
} else { }
}, function() {
if (childInputHasFocus) {
// do something
} else { }
});
$('input', this)
.focus(function(){
childInputHasFocus = true;
})
.blur(function(){
childInputHasFocus = false;
});
});
An alternative to using classes to mark the state of an element is the internal data store functionality.
P.S.: You are able to store booleans and whatever you desire using the data() function. It's not just about strings :)
$("...").mouseover(function ()
{
// store state on element
}).mouseout(function ()
{
// remove stored state on element
});
And then it's just a matter of accessing the state of elements.
if anyone cares there is a much better way to capture focus now, $(foo).focus(...)
http://api.jquery.com/focus/
Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave
Keep track of both states (hovered, focused) as true/false flags, and whenever one changes, run a function that removes border if both are false, otherwise shows border.
So: onfocus sets focused = true, onblur sets focused = false. onmouseover sets hovered = true, onmouseout sets hovered = false. After each of these events run a function that adds/removes border.
As far as I know, you can't ask the browser if any input on the screen has focus, you have to set up some sort of focus tracking.
I usually have a variable called "noFocus" and set it to true. Then I add a focus event to all inputs that makes noFocus false. Then I add a blur event to all inputs that set noFocus back to true.
I have a MooTools class that handles this quite easily, I'm sure you could create a jquery plugin to do the same.
Once that's created, you could do check noFocus before doing any border swapping.
There is no :focus, but there is :selected
http://docs.jquery.com/Selectors/selected
but if you want to change how things look based on what is selected you should probably be working with the blur events.
http://docs.jquery.com/Events/blur
There is a plugin to check if an element is focused: http://plugins.jquery.com/project/focused
$('input').each(function(){
if ($(this) == $.focused()) {
$(this).addClass('focused');
}
})
I had a .live("focus") event set to select() (highlight) the contents of a text input so that the user wouldn't have to select it before typing a new value.
$(formObj).select();
Because of quirks between different browsers, the select would sometimes be superseded by the click that caused it, and it would deselect the contents right after in favor of placing the cursor within the text field (worked mostly ok in FF but failed in IE)
I thought I could solve this by putting a slight delay on the select...
setTimeout(function(){$(formObj).select();},200);
This worked fine and the select would persist, but a funny problem arose.. If you tabbed from one field to the next, the focus would switch to the next field before the select took place. Since select steals focus, the focus would then go back and trigger a new "focus" event. This ended up in a cascade of input selects dancing all over the screen.
A workable solution would be to check that the field still has focus before executing the select(), but as mentioned, there's no simple way to check... I ended up just dispensing with the whole auto highlight, rather than turning what should be a single jQuery select() call into a huge function laden with subroutines...
What I wound up doing is creating an arbitrary class called .elementhasfocus which is added and removed within the jQuery focus() function. When the hover() function runs on mouse out, it checks for .elementhasfocus:
if(!$("#quotebox").is(".boxhasfocus")) $(this).removeClass("box_border");
So if it doesn't have that class (read: no elements within the div have focus) the border is removed. Otherwise, nothing happens.
Simple
<input type="text" />
<script>
$("input").focusin(function() {
alert("I am in Focus");
});
</script>

Categories