jQuery - remove element on blur BUT catch click on his children - javascript

I have following code:
$('#myEl').blur(function(){
$(this).remove('.children');
});
But the children element have links inside, with another jQuery actions which doesn't trigger because the .children is removed on blur, which I guess is triggered before the click action. Simple example:
Children is visible and #myEl have focus
I click on the children link
#myEl loses his focus
Children element is removed
Children link action is not triggered, because I guess link is not present anymore
How to solve this? I was trying to delay remove:
$(this).delay(100).remove('.children');
With no luck.

If you are working with the delay way, you can't use jQuery .delay() since it only work on queued element (with animation).
You can use setTimeout :
$('#myEl').blur(function(){
var $this = $(this);
setTimeout(function(){
$this.remove('.children');
}, 100)
});

I've tried it with mousedown event and it worked fine. I don't thing adding a delay is always a good option.
<input type="text" id="myEl"></input>
<div class="children" >div child</div>
<script>
$('#myEl').blur(function(e){
$('.children').remove();
});
$(".children").mousedown(function() {
window.open('http://www.google.com')
});
</script>
And if you really want to add the click event for a specific reason then you can try this:-
$('#myEl').blur(function(e){
if(mousedown){
window.open('http://www.google.com');
mousedown = false;
}
$('.children').remove();
});
$('.children').click(function(e){
window.open('http://www.google.com')
});
$(".children").mousedown(function() {
mousedown = true
});

what about simply making the child elements hidden after a click? Or maybe even having the child itself remove all children from its parent container after it has processed the click?
$('#myEl').blur(function(){
$(this).children('.children').hide();
});
$('.children').on("click",function(){
// perform your click-code actions here
alert("I did it!");
// now remove your child elements from the parent
$(this).parent().children('.children').remove();
});

Related

Jquery toggle div, allow clicking outside of div to close, also allow everything inside the div clickable

I have a toggle event on a div, and I've seen many questions regarding mine but nothing seems to work for what I'm trying to do, it either makes my div disappear in a few seconds, or it just doesn't work. Here's my jsfiddle.
I have a div that needs to toggle when another <div> is clicked. The toggled div has inputs in it that need to be filled out, and a submit button inside it as well. So I need clicks inside the div to be allowed, but only inside my div. So I want the div to show unless the user clicks outside of this div.
I'm using this query which toggles fine:
$('#MyDiv').click(function (event) {
$("#ToggledDiv").slideToggle();
});
And then this coding to hide it when clicked outside of the div which doesn't work:
$(window).click(function () {
$("ToggledDiv").hide();
});
I've tried solutions with e.preventDefault(); but that doesn't work, or $(document).click, even mousedown but it just doesn't flow how I want, it'll hide it within a few seconds, or it will prevent the toggle from even working so I'm lost.
The reason behind this behavior is Event Bubbling and Capturing of HTML DOM API. You can use event.stopPropagation() OR event.cancelBubble = true to prevents the event from bubbling up to the DOM tree, preventing any parent handlers from being notified of the event.
Another good article: events order
$('#MyDiv').click(function(event) {
$("#ToggledDiv").show();
disabledEventPropagation(event);
//console.log('2nd event');
});
$('#ToggledDiv').click(function(event) {
disabledEventPropagation(event);
//console.log('3rd event');
});
$(document).click(function() {
$("#ToggledDiv").hide();
//console.log('1st event');
});
function disabledEventPropagation(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (window.event) {
window.event.cancelBubble = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MyDiv" style="background-color:yellow">
click me to open
</div>
<div id="ToggledDiv" style="display: none;background-color:yellow">
<input type="text" />
<input type="submit" />
</div>
Take a look at the event when you click inside the #targetDiv. There are two properties you can use to evaluate what action to perform: event.target and event.currentTarget. In this case:
$('#ToggledDiv').on('click', function(event) {
console.log(event.target, event.currentTarget);
});
This is a good way to see if what clicked is actual target or a child element in the target.
To add to Chris' answer, you can see here that I check that the e.target is not inside the form using vanilla Node.contains, and also not the button...
https://jsfiddle.net/jmLdp45s/3/
var $button = $('button');
var $form = $('form');
$button.click(function() {
$form.slideToggle();
});
$(window).click(function(event) {
if (
!$form.get(0).contains( event.target ) // target is not inside form
&& event.target !== $button.get(0) // target is not button
) $form.hide();
});

Two OnClick events overlap

I have an element inside an element, when I click the element underneath I want the slider to open. When I click on the outermost element I want the slider to close.
Unfortunately when I click on the outermost it clicks the underneath element as well. Is there a way to click only on the outermost element ignoring the click on the underneath element? The events are triggered on click and executed with javascript.
I tried with z-index but it still captures the underneath element clicked as well, and because the functions are contrary to one another nothing happens.
edit: on a "code is worth 1000 words" tip
var $target = $(this).data('pos', i) //give each li an index #
$target.data('hpaneloffsetw', $target.find('.hpanel:eq(0)').outerWidth()) //get offset width of each .hpanel DIV (config.dimensions.fullw + any DIV padding)
$target[haccordion.ismobile? "click" : "mouseenter"](function(){
haccordion.expandli(config.accordionid, this)
config.$lastexpanded=$(this)
})
if (config.collapsecurrent){ //if previous content should be contracted when expanding current
$('.close').click(function(){
$target.stop().animate({width:config.paneldimensions.peekw}, config.speed) //contract previous content
})
$target.dblclick(function(){
$(this).stop().animate({width:config.paneldimensions.peekw}, config.speed) //contract previous content
})
}
Because the code is borrowed, I don't understand much of it. But basically I want the "click" : "mousteenter" function to work on click, without interfering with the .close().click
It sounds like you need to stop the click event bubbling up the DOM to be caught by parent elements. You can use stopPropagation() to do this:
$('.close').click(function(e) {
e.stopPropagation();
$target.stop().animate({ width: config.paneldimensions.peekw }, config.speed);
})
$target.dblclick(function(e) {
e.stopPropagation();
$(this).stop().animate({ width: config.paneldimensions.peekw }, config.speed);
})
Try the following fiddle
$("#outer").click(function(){alert("outer clicked")});
$("#inner").click(function(e){
alert("inner clicked")
e.stopPropagation();
});
To identify the element you have "really" clicked on, you can try to identify it through accessing the target property of the jquery-event-object.
After you identified the target you clicked on, you could prevent other event handlers from firing.
Use CSS specific jquery to point exact element like below, use > to point exact child
table > tbody > tr > td > input[type='text']
like this.

D3 remove click events from one element out of a selection

I have a class in D3 say: selectors and I need to remove the click event from the selection
d3.selectAll('.selectors').on('click',function(){
//Remove the currently clicked element from the selection.
});
Ive got two problems:
The removed element is supposed to be moved to a different part of the page and the I need the click event on it to be removed.
Also, would it be possible to reinsert the removed element into the selection on doing something else, like clicking on the removed element again?
Edit:
Found a solution for problem 1
d3.selectAll('.selectors').on('click',function(){
//Remove the currently clicked element from the selection.
d3.select(this).on('click',null);
});
Is this the right way? Or is there a more graceful method?
A Demo Fiddle
here is the updated jquery it will work for your case
$(document).ready(function(){
$(document).on('click','.selectors',function(e){
//$(document).off( 'click','.selectors');
if(e.target.onclick==null)
{
e.target.onclick=
function(){
void(0);
};
alert('test');
console.log('Hello');
}
});
});
For problem 1, the best method(as far as I know) is to redefine the click event in D3 itself:
d3.selectAll('.selectors').on('click',function(){
//Remove the currently clicked element from the selection.
d3.select(this).on('click',null);
});
For problem 2, however, once you turn a click event callback to null, the only way is to redefine the click event again, perhaps recursively:
function clickDefine() {
d3.selectAll('.selectors').on('click', function () {
//Remove the currently clicked element from the selection.
console.log('Hello')
d3.select(this).on('click', null);
setTimeout(function(){clickDefine();},1000)
});
}
This function makes the click event inactive for 1 second on click. And reactivates this again. I'm hoping this is an effective solution.

Close popup div if element loses focus

I have the following scenario: On a label's mouseover event, I display a div. The div must stay open in order to make selections within the div. On the label's mouseout event, the div must dissappear. The problem is that when my cursor moves from the label to the div, the label's mouseout event is fired, which closes the div before I can get there. I have a global boolean variable called canClose which I set to true or false depending on the case in which it must be closed or kept open. I have removed the functionality to close the div on the label's mouseout event for this purpose.
Below is some example code.
EDIT
I have found a workaround to my problem, event though Alex has also supplied a workable solution.
I added a mouseleave event on the label as well, with a setTimeout function which will execute in 1.5 seconds. This time will give the user enough time to hover over the open div, which will set canClose to false again.
$("#label").live("mouseover", function () {
FRAMEWORK.RenderPopupCalendar();
});
$("#label").live("mouseout", function () {
setTimeout(function(){
if(canClose){
FRAMEWORK.RemovePopupCalendar();
}
},1500);
});
this.RenderPopupCalendar = function () {
FRAMEWORK.RenderCalendarEvents();
}
};
this.RenderCalendarEvents = function () {
$(".popupCalendar").mouseenter(function () {
canClose = false;
});
$(".popupCalendar").mouseleave(function () {
canClose = true;
FRAMEWORK.RemovePopupCalendar();
});
}
this.RemovePopupCalendar = function () {
if (canClose) {
if ($(".popupCalendar").is(":visible")) {
$(".popupCalendar").remove();
}
}
};
Any help please?
I would wrap the <label> and <div> in a containing <div> then do all you mouse/hide events on that.
Check out this fiddle example - http://jsfiddle.net/6MMW6/1
Give your popupCalendar an explicit ID instead of a class selector, e.g.
<div id="popupCalendar">
Reference it with #popupCalendar instead of .popupCalendar.
Now, remove() is quite drastic as it will completely remove the div from the DOM. If you wish to display the calendar again you should just .hide() it.
But your logic seems a bit overly complex, why not just .show() it on mouseenter and .hide() on mouseout events ?
This will close the entire tab page if the tab page loses focus.
How ever if you target it, it can work for something within the page too, just change the target codes.
JavaScript:
<script type="text/javascript" >
delay=1000 // 1 sec = 1000.
closing=""
function closeme(){
closing=setTimeout("self.close()",delay)
// self means the tab page close when losing focus, but you can change and target it too.
}
<!--// add onBlur="closeme()" onfocus="clearTimeout(closing)" to the opening BODY tag//-->
</script>
HTML:
<body onBlur="closeme()" onfocus="clearTimeout(closing)">

Trigger event on specific condition

I have a div that will serve as container to other element, I have buttons that add element to that div.
Please see the demo for a get an idea about it.
So, what I want to do is to check before adding a new element is the div reached a maximum number of elements that I define, let's say 4.
I can check this condition before every add, but I am sure this is not the best way (we learned that if the code contains copy/paste then is not the best solution) Also, this is just a sample, in my case, I have many buttons..
Is there a way to have a listener like this?
$('#container').bind('divFull', function(){
//My code
});
So that I can disable buttons..
First, you have to listen to DOM change event, then you can trigger a custom event based on the number of children
$('#container').bind('DOMSubtreeModified', function(){
if($(this).children().length>=4){
$(this).trigger('divFull');
}
});
then you can bind to your custom divFull event
$('#container').bind('divFull', function(){
alert('container is full');
$('button').prop('disabled',true);
});
a working demo based on your example
I change a bit the #skafandri method because the event DOMSubtreeModified doesn't work on IE < 9 and it's depreciated.
The main change is to create a function which will call the divFull event if their is 4 children in the container.
var checkFull = function() {
if ($container.children().length === 4) {
$container.trigger('divFull');
}
}
$('#button1').click(function(){
$container.append('<div class="element">some text</div>');
checkFull();
});
Here is the demo.

Categories