JQuery: don't focus out when clicking on something - javascript

I have a div, #someDiv, on which I have some jQuery code to execute when focused on, and when focused out. But I want to achieve an action in which, if a certain other div is clicked on when div #1 is focused on, that focus remains on the div:
$(document).on("focus", "#someDiv", function() {
// Some code here to execute
}).on("focusout", "#someDiv", function() {
if (#someDiv2 was clicked on) { // DON'T focus out from #someDiv }
});
...however the issue is that jQuery is unable to distinguish that during the focus out, a click was made. How can I achieve this effect?
EDIT: Basically the idea I am trying to implement is a mock web-app in which you can customize a certain kind of div when it has focus, and upon that, an "options" div appears. I don't want the options bar to disappear when it is clicked, as otherwise none of the "options" can be chosen.

One half baked solution is to simply monitor the time for click / blur and correlate the two:
http://jsfiddle.net/ztA5F/
var lastBlur = new Date().getTime();
$("html").on("click", function() {
var now = new Date().getTime();
console.log(lastBlur);
console.log(now);
if (lastBlur >= (new Date().getTime() - 500))
$("#input").focus();
console.log("click");
});
$("#input").on("blur", function() {
lastBlur = new Date().getTime();
console.log("blur");
});

I am not certain I totally understand what you're after, but maybe this will be helpful:
var lastID;
$(document).on('click focus', function (e) {
var id = $(e.target).attr('id');
if (id === 'someDiv2' && lastID === 'someDiv') {
$('#someDiv').trigger('focus');
}
lastID = id;
});

Related

jQuery animation skipped when clicking quickly

Please take a look at this jsfiddle
If you click on the divs on the top quickly enough, you'll find that eventually two divs end up appearing. I've had this problem with jQuery before as well. I just ended up disabling the buttons (or animation triggers) in that case, but I'm wondering if there is a more elegant solution to this.
Here is my jQuery code -
$(function () {
var _animDuration = 400;
$("#tabLists a").click(function () {
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function () {
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function () {
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
})
});
return false;
});
});
I'm using callbacks everywhere. I would like a solution that would queue up the animation rather than, not allow me to click
try this code with a check var:
$(function(){
var check = 1;
var _animDuration = 400;
$("#tabLists a").click(function(){
if(check == 1){
check = 0;
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function(){
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function(){
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
check = 1;
})
});
}
return false;
});
});
DEMO

Do not fire one event if already fired another

I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});​
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});

Javascript click event take place only after javascript has completely driven

I have javascript in my page and I use there the click event. The problem is that in ie the clicking doesnt't hapen right away, but only after the hole javascript has gone through.
Then it fires that click event!
I would need it to hapen right away, before the other javascript-code!
$(document).ready(function() {
// sorting the list
var myLink = document.getElementById('header3');
myLink.click();
// scrolling the list to where the modified row is
if ('${rowId}') {
var row = $('#row-${rowId}');
row.addClass("highlight");
var scrollParent = ((jQuery.browser.msie) ? row.parent().parent().parent()[0] : row.parent()[0]);
row[0].scrollIntoView(false);
if (scrollParent.scrollTop > 0)
scrollParent.scrollTop = scrollParent.scrollTop + (scrollParent.clientHeight / 2);
}
}
That sorting should happen before scrolling! In ie the clicking happens after scrolling and then the scrolling is in wrong place.
In Firefox this works!
Can you help me on this?
Assuming (never a good thing) that the code that is executing before the click event code is the code you enter here below the click() call, why don't you refactor that to a function and make it part of the code that happens when you call the click() code?
Try this. Place your code in a separate function and trigger that function within the click.
$(function(){
function yourfunction(event)
{
//code to be executed after the click
// scrolling the list to where the modified row is
if ('${rowId}') {
var row = $('#row-${rowId}');
row.addClass("highlight");
var scrollParent = ((jQuery.browser.msie) ? row.parent().parent().parent()[0] : row.parent()[0]);
row[0].scrollIntoView(false);
if (scrollParent.scrollTop > 0)
scrollParent.scrollTop = scrollParent.scrollTop + (scrollParent.clientHeight / 2);
}
return false;
}
});
$(document).ready(function() {
// sorting the list
$('#header3').click(yourfunction);
});
Hope it helps,
Cumps

Prevent 'click' event from firing multiple times + issue with fading

Morning folks. Have an issue with a simple jQuery gallery i'm making. It lets the user cycle through a collection of images via some buttons and at the same time, rotates through these images on a timer. My problem is that the user is able to click the button multiple times which queues up the fade in animation and repeats it over and over, e.g. user clicks button 5 times > same image fades in/out 5 times > gallery moves to next image.
I've tried using:
$('#homeGalleryImage li a').unbind('click');
After the click event is fired and then rebinding:
$('#homeGalleryImage li a').bind('click');
After it's done but this simply removes the click event after pressing a button once and never rebinds to it?
I've also tried disabling the button via:
$('#homeGalleryImage li a').attr('disabled', true);
To no avail... ?
There is a secondary issue where if you manage to click a button while the image is in a transition, the next image appears 'faded' as if the opacity has been lowered? Very strange... Here is the code for button clicks:
var i = 1;
var timerVal = 3000;
$(function () {
$("#homeGalleryControls li a").click(function () {
var image = $(this).data('image');
$('#galleryImage').fadeOut(0, function () {
$('#galleryImage').attr("src", image);
});
$('#galleryImage').fadeIn('slow');
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(this).find('img').attr("src", "/Content/Images/Design/btn_checked.gif");
i = $(this).data('index') + 1;
if (i == 4) {
i = 0;
}
timerVal = 0;
});
});
Here is the code that cycles through the images on a timer:
//Cycle through gallery images on a timer
window.setInterval(swapImage, timerVal);
function swapImage() {
$('#galleryImage').fadeOut(0, function () {
var imgArray = ["/Content/Images/Design/gallery placeholder.jpg", "/Content/Images/Design/1.jpg", "/Content/Images/Design/2.jpg", "/Content/Images/Design/3.jpg"];
var image = imgArray[i];
i++;
if (i == 4) {
i = 0;
}
$('#galleryImage').attr("src", image);
$('#galleryImage').fadeIn('slow');
});
var currentButton = $('#homeGalleryControls li a img').get(i - 1);
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(currentButton).attr("src", "/Content/Images/Design/btn_checked.gif");
}
I realise it might be a better idea to use a plugin but I'm very new to jQuery and I'd like to learn something rather than using some ready made code.
Any help at all, is much appreciated.
Thankyou
You could always try adding something to the element to cancel the click event?
For example
$(".element").click(function(e) {
if ( $(this).hasClass("unclickable") ) {
e.preventDefault();
} else {
$(this).addClass("unclickable");
//Your code continues here
//Remember to remove the unclickable class when you want it to run again.
}
}):
In your case you could try adding a check on the click.
$('#homeGalleryImage li a').attr('data-disabled', "disabled");
Then inside your click event
if ( $(this).attr("data-disabled" == "disabled") {
e.preventDefault();
} else {
//Ready to go here
}
Edit
Here is a working example showing the element becoming unclickable. http://jsfiddle.net/FmyFS/2/
if you want to make sure that the registered event is fired only once, you should use jQuery's one :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using vanilly JS: https://codepen.io/loicjaouen/pen/gOOBXYq
// add a listener that run only once
button.addEventListener('click', once_callback, {capture: true, once: true});

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.
The problem most likely lies somewhere within the click event. Here is the code:
$('#tab-list li a').click(
function() {
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:
if ($(':animated')) {
// Don't do anything
}
else {
// Do transition
}
But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.
If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating).
On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes.
var blockAnimation = false;
$('#tab-list li a').click(
function() {
if(blockAnimation != true){
blockAnimation = true;
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow', function(){ blockAnimation=false; });
}
);
}
}
return false;
}
);
Well this is how i did it, and it worked fine.
$(document).ready(function() {
$(".clickitey").click(function () {
if($("#mdpane:animated").length == 0) {
$("#mdpane").slideToggle("slow");
$(".jcrtarrow").toggleClass("arrow-open");
}
});
});
this is not doing what your code does ofcourse this is a code from my site, but i just like to point how i ignored the clicks that were happening during the animation. Please let me know if this is inefficient in anyway. Thank you.
I toyed around with the code earlier and came up with the following modification which seems to work:
$('#tab-list li a').click(
function() {
$('.tab:animated').stop(true, true);
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
All that happens is, when a new tab is clicked, it immediately brings the current animation to the end and then begins the new transition.
one way would be this:
$('#tab-list ul li').one( 'click', loadPage );
var loadPage = function(event) {
var $this = $(this);
$global_just_clicked = $this;
var urlToLoad = $this.attr('href');
$('#content-area').load( urlToLoad, pageLoaded );
}
$global_just_clicked = null;
var pageLoaded() {
$global_just_clicked.one( 'click', loadPage );
}
As you can see, this method is fraught with shortcomings: what happens when another tab is clicked before the current page loads? What if the request is denied? what if its a full moon?
The answer is: this method is just a rudimentary demonstration. A proper implementation would:
not contain the global variable $global_just_clicked
not rely on .load(). Would use .ajax(), and handle request cancellation, clicking of other tabs etc.
NOTE: In most cases you need not take this round-about approach. I'm sure you can remedy you code in such a way that multiple clicks to the same tab would not affect the end result.
jrh.
One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});

Categories

Resources