If else statement for javascript click event - javascript

I have two statements. What I am trying to do is when someone clicks on #area_a then hide then entire #area_b div without activating the focusout for the #area_b_textbox. But I've tried different code (which I am not including here because it is incorrect and want to get your suggestions) and what is happening is it is activating the focusout everytime I click on the #area_a div.
JQuery base actions
$("#area_a").click(function() { $("#area_b").hide(); });
$("#area_b_textbox").focusout(function() {$("#area_b_error").show();});
HTML:
<div id="area_a"></div>
<div id="area_b">
<input id="area_b_textbox">
<div id="area_b_error"></div>
</div>
Thanks!

You could hack around the problem with a timer. Timers usually smell bad but I think it is your safest bet here. If you try using hover or other mouse events you might run into trouble with keyboard navigation and activation or the lack of "hoverish" events on touch interfaces (and we can't pretend those don't exist anymore).
Something like this:
var timer_kludge = {
start: function(fn) {
this.id = setTimeout(fn, 200);
},
stop: function() {
if(this.id)
clearTimeout(this.id);
this.id = null;
},
id: null
};
$('#area_a').click(function() {
timer_kludge.stop();
$('#out').append('<p>click</p>');
});
$('#area_b_textbox').focusout(function() {
timer_kludge.start(function() {
$('#out').append('<p>textarea focusout</p>');
});
});
$('#area_b_textbox').focusin(function() {
timer_kludge.stop();
});
Demo: http://jsfiddle.net/ambiguous/s8kw8/1/
You'd want to play with the 200 timeout a bit to see what works best in your circumstances.

Why not just add a flag to ignore next focusout (blur?) event.
ignoreNextFocus = false;
$("#area_a").click(function() { ignoreNextFocus=true; $("#area_b").hide(); });
$("#area_b_textbox").focusout(function() { if(!ignoreNextFocus)$("#area_b_error").show();ignoreNextFocus=false;});
On that note setting the flag on click event might be too late. If it is the case, try mousedown event.

this is not possible since you loose the focus automatically when you click somewhere else...
What you need to do is to unbind the focusout event on hover of the #area_a and rebind it later on...
$("#area_a").click(function() {
$("#area_b").hide()
}),hover(
function(){
$("#area_b_textbox").unbind("focusout")
},
function(){
$("#area_b_textbox").focusout(function() {$("#area_b_error").show();});
}
)
PS: what is your ultimate goal here?

I'm not sure this is possible since by definition the focus has to leave the #area_b_textbox if the user is going to click a button.

Related

trigger function if scroll reaches a certain point only once. Not every time

I want to check if my users arrive at a certain point in my page. SO I created the following JS code:
$(document).on('scroll', function() {
if($(this).scrollTop()>=$('#page2').position().top){
alert("trigger");
}
})
Which checks if the users reached my id="page2". But I want this to trigger ONLY once, no matter if the users goes back up and back down, right now it gets trigger everytime the page2.position().top = scrollTop.
How can I do this ?
You can use event.namespace and off() to unbind event handler after execution of desired statement.
$(document).on('scroll.something', function() {
if ($(this).scrollTop() >= $('#page2').position().top) {
//Do something
//Unbind the event
$(document).off('scroll.something')
}
})
You can use this code to achieve your desired output.
var checkonce = false;
$(document).on('scroll', function() {
if($(this).scrollTop()>=$('#page2').position().top){
if(checkonce == false) {
alert("trigger");
checkonce = true;
}
}
});
You can just off the scroll event on your document after the first scroll has reached.
Edit: Also it would be better if you name your events, Which will help us remove the specific event by using the name. (Satpal already mentioned this in his answer before me, I am improving my answer standard as well.)
$(document).on('scroll.Page2ScrollEvent', function() {
if($(this).scrollTop()>=$('#page2').position().top){
$(this).off('scroll.Page2ScrollEvent'); // remove specific scroll event.
alert("trigger");
}
})

Prevent parent event from triggering child events

So there are plenty of questions asking how to keep child events from triggering parent events, but I can't seem to find any for the opposite.
I toggle a parent event on and off like so:
var body_event = function(e){
console.log('test');
};
$('#btn').toggle(
function(e){
$('body').bind('click', body_event);
},
function(){
$('body').unbind('click', body_event);
}
);
Currently if I run this on a page like this:
<body>
<div id="btn">click to activate</div>
<div id="example" onclick="alert('do not show this when event is bound')">
try the body event by clicking here
</div>
</body>
the toggle works fine, but when I click on "try the body event by clicking here" the alert will still show up. I want to be able to ignore all child events when the body event is bound without individually referencing the child events.
In other words I'm looking for a better solution than doing something like this on toggle:
$('#example").attr('onclick', '');
This is close, but not quite there. It doesn't check whether the specific function is bound, just whether there are any events bound to the jQuery object.
There must be a way to query the events to find if one is bound to click, and then subsequently what function it points too. Hopefully this gets you started though.
http://jsfiddle.net/PhjB8/
var body_event = function(e) {
alert('test');
};
$('#btn').toggle(
function(e) {
$('body').addClass('active').bind('click', body_event);
}, function() {
$('body').removeClass('active').unbind('click', body_event);
});
$('#example').click(function() {
//debugger;
if ($('body').data('events') == undefined) {
alert('do not show this when event is bound');
}
});​
event.stopPropagation() can solve this problem, inside body_event?

How defined in jQuery was it a regular click on the same element or double-click?

How can I define in jQuery was it a regular click on the same element or double-click?
For example we have element like this:
<div id="here">Click me once or twice</div>
And we need to perform different actions after regular click and double-click.
I tried something like this:
$("#here").dblclick(function(){
alert('Double click');
});
$("#here").click(function(){
alert('Click');
});
But, of course, it doesn't work, everytime works only 'click'.
Then, some people showed me this:
var clickCounter = new Array();
$('#here').click(function () {
clickCounter.push('true');
setTimeout('clickCounter.pop()', 50);
if (clickCounter.length > 2) {
//double click
clickCounter = new Array(); //drop array
} else {
//click
clickCounter = new Array(); //drop array !bug ovethere
}
});
Here we tried to set the interval between clicks, and then keep track of two consecutive events, but this have one problem.. it doesn't work too.
So, someone knows how to do this? or can someone share a link to the material, where I can read about it?
From QuirksMode:
Dblclick
The dblclick event is rarely used. Even when you use it, you should be
sure never to register both an onclick and an ondblclick event handler
on the same HTML element. Finding out what the user has actually done
is nearly impossible if you register both.
After all, when the user double–clicks on an element one click event
takes place before the dblclick. Besides, in Netscape the second click
event is also separately handled before the dblclick. Finally, alerts
are dangerous here, too.
So keep your clicks and dblclicks well separated to avoid
complications.
(emphasis mine)
What you are doing in your question, is exactly how it should be done.
$(".test").click(function() {
$("body").append("you clicked me<br />");
});
$(".test").dblclick(function() {
$("body").append("you doubleclicked me<br />");
});
It works and here is an demo for that.
Since, you want to detect separate single double click. There is a git project for this.
$("button").single_double_click(function () {
alert("Try double-clicking me!")
}, function () {
alert("Double click detected, I'm hiding")
$(this).hide()
})
It adds up events to detect single double clicks.
Hope it helps you now.

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();
}
});

Add click event to Div and go to first link found

I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});

Categories