child click event firing parent mouseover event - javascript

I have tree structure in which mouse over on node name displays (UL) list. Each item in the list has a click event attached to it. The issue Im facing is when I click on any child item in list, it fires the mouseover event attached to parent span. Can you guys please help how to solve this issue?
<span id="treeNodeText">
<ul><li id="firstItem">First Item</li></ul>
</span>
My code is like this:
I have conman event attach method:
attachEvents(domId,eventType,callBackFunction,otherParams)
In attachEvent function I attach events to dom ids and assign appropriate call back functions

The mouseover event is fired before you click. So, apart with a delay, you can't prevent its handling.
Here's one way to deal with that :
var timer;
document.getElementById("treeNodeText").addEventListener('mouseover', function(){
clearTimeout(timer);
timer = setTimeout(function(){
// handle mouseover
}, 400); // tune that delay (depending on the sizes of elements, for example)
});
document.getElementById("firstItem").addEventListener('click', function(){
clearTimeout(timer); // prevents the mouseover event from being handled
// handle click
};

In JavaScript, events bubble up the DOM. Please read more about it: event order and propagation or preventDefault/stopPropagation.
In short, you can pervent event bubbling by
function callBackFunction(event){
event.stopPropagation()
}
or
function callBackFunction(event){
return false
}
return false also has the effect of preventing the default behavior, so it's technically equivalent to:
function callBackFunction(event){
event.stopPropagation()
event.preventDefault()
}

function myfunction(e){
e.stopPropagation()
e.preventDefault()
}
this will Help

Related

Not calling click event

I have kind of strange problem.
I'm trying to add a couple of events to som DOM elements (all existing, some initially hidden:
$self.on("focus", function () {
$self.next().css("display", "inline-block");
});
$self.on("blur", function () {
$(this).next().hide();
});
$self.parent().find(".icon-ok").on("click", function() {
console.log("icon.ok")
});
You can see the relevant part of the DOM here (self is the span user-name):
Later on, the element eventually because visible and I can click on it. However, the event handler is never called. If I remove the blur event, than the click event works. However, I need both.
What's going on here?
How can I fix it?
Looks like the blur cancels out the click (due to event order) but using mousedown instead of blur may help you get both.
UPDATE: Added code based on comment
$self.parent().find(".icon-ok").on("mousedown", function() {
console.log("icon.ok")
});
Your problem might be the classic delegation problem, where in the element is not available in the DOM when the event is bound.
Delegate the event and see if that solves your problem.
$self.on("click", ".icon-ok", function() {
console.log("icon.ok")
});
User $self if that element is visible or any closest ancestor that you can find which is always present in the DOM.

jQuery - Event delegation is occuring multiple times

I'm using event delegation in the pagination for my website. When you click the < or > buttons it moves the page up or down. The problem is that if you don't release the mouse button, in a split-second it will keep repeating the click handler.
How can I make it so that this event only occurs once per-click? Here's my code:
$(document).on('mousedown', '#prev', function(event) {
// Page is the value of the URL parameter 'page'
if (page != 1) {
page--;
var state = {
"thisIsOnPopState": true
};
history.replaceState(state, "a", "?page=" + page + "");
}
// Refresh is a custom function that loads new items on the page
refresh();
});
You should use "click" event instead of "mousedown" unless you have a unavoidable reason.
But "mousedown" or "touchstart" event occurs when a user start pressing the mouse button or screen and it will not be fired until you release the button and press it again.
So I assume you are using a chattering mouse or mouses which has macro software.
change event into "click" and see if it works and in the case "click" event is not gonna solve the issue,try using another mouse.
FYI,underscore methods _.throttle or _.debounce might help to support chattering mouses.
throttle_.throttle(function, wait, [options])
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
debounce_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.
http://underscorejs.org/
If you want to use a "delegated" event handler rather than a "direct" event handler to bubble up the event, try to use a more specific target selector than $(document) like $('.some-class') where some-class is the class name directly above the #prev element.
I would also use either the mouseup or click events instead to avoid the mousedown event firing while the mouse click is held down.
According to the API:
The majority of browser events bubble, or propagate, from the deepest,
innermost element (the event target) in the document where they occur
all the way up to the body and the document element.
Try this:
// delegated "click" listener using a more specific target selector
$('.some-class').on('click', '#prev', function(event) {})
You may want to check your HTML to see if you are using #prev multiple times. Usually, just creating the listener on the target ID element should work fine.
// direct "click" listener on an ID element
$('#prev').on('click', function(event) {})
I haven't found the answer to this question, but I have found a solution that fixes the problem. What I have done is added a conditional that only allows the click event to occur once-per-click:
var i = 0;
$(document).on('click', '#prev', function(event) {
if (page != 1 && i === 0) {
page--;
var state = {
"thisIsOnPopState": true
};
history.replaceState(state, "a", "?page=" + page + "");
i = 1;
refresh();
}
});
// Resets 'i' for the next click
$(document).on('mouseup', function() {
i = 0;
});

Why document click listener triggers immediately?

I want to bind a click function to the document when open some menu via click.
The problem is that when trigger the first event 'click on the menu', the function attached to the document has been triggered by the same event and close the menu. How to solve that issue. My code is something like that:
$('#openMenu').bind('click touchend', function(e){
e.preventDefault();
$('.openMobMenu').removeClass('openMobMenu');//Close All elements
var _this=$('#headMenu')
_this.addClass('openMobMenu');
$(document).bind('click touchend',{elem:_this},hideElementMob);
});
// bind click event listner to the document
function hideElementMob(e){
var th=e.data.elem;//Get the open element
var target=$(e.target);//Get the clicked target
//Check the target and close the element if need
if(target.parents('.openMobMenu').length==0) {
th.removeClass('openMobMenu');//close the element if need
//Unbind listner after closing the element
$(document).unbind('click touchend');
}
}
Thank you in advance!
Try adding the close handler with a little delay:
setTimeout(function(){
$(document).bind('click touchend',{elem:_this},hideElementMob);
}, 10);
And as Jan Dvorak suggested, you should use .on() to attach events.
UPDATE
I realized I did not answer the whole question, so here is some improvement to the "why does it behave like this" part:
When the click event occurs on #openMenu, the associated handler is executed first. This binds a click event to the document body itself.
After this, the event gets bubbled, so the parents of the #openMenu also recieves a click event, and since document.body is a parent of the #openMenu, it also recieves a click event and closes the popup immediatley.
To cancel the event bubbling, you can also call e.stopPropagation(); anywhere in your event handler. (maybe its a cleaner solution compared to setTimeout)

jQuery stopPropagation is ignored

My goal is to prevent all the click events (hiding/showing of elements in the HTML when clicked) unless a certain condition is met (the user has a certain word in an input element).
So i tried to add that logic to the click handler of the document or "html" but the click handler of the other element fired first because of bubble up.
So i tried attaching that logic to "*", and now that click handler fires first- but propagates it to the the other element too, ignoring stopPropagation, preventDefault and return false.
$(document).ready(function(){
$("*").click(function(event){
if ($("#user").val() !== "admin"){
console.log("1");
event.stopPropagation();
event.preventDefault();
return false;
}
});
$("#user").click(function(event){
console.log("2");
// do something
});
});
Why "2" is written to the console after "1" when there shouldn't be any further propagation because of return false/stopPropagation?
How else can i achieve my goal using jQuery?
Thanks!
stopPropagation() prevents the event propagating any further up the ancestor tree. However, it doesn't prevent the remaining event handlers on the current from being fired.
To do this (prevent further propagation and prevent any further event handlers on the current element from being fired), you need to call stopImmediatePropagation() (instead, not as well).
Attaching an event handler to every element in this manner, and calling stopImmediatePropagation() (as well as preventDefault()) will prevent all clicks from having an effect; providing no event handlers are bound before (as handlers are executed in order; you can't undo a handler which has already fired).
This doesn't make it nice though, as finding, enumerating over, and attaching a handler to every element is pretty costly.
To make it nicer, your options are either:
Attach a click event to document, and simply preventDefault() and sacrifice stopImmediatePropagation().
Check the state of #user in each event handler; you can ease the pain of this by rolling your own wrapper function;
function checkUserState(then) {
return function () {
if ($("#user").val() !== "admin") {
then.apply(this, arguments);
}
};
};
... use like so;
$("#user").click(checkUserState(function(event){
console.log("2");
}));
As noted in the comments, I'm purposefully avoiding the suggestion of using event delegation, as whilst allows attaching only one event handler instead of n, it doesn't allow you to stopPropagation() of events.

Set the mouseover Attribute of a div using JQuery

I would like to set an attribute for a div. I have done this:
$('#row-img_1').onmouseover = function (){ alert('foo'); };
$('#row-img_2').onmouseout = function (){ alert('foo2'); };
However, the above has not worked, it does not alert when mouse is over or when it moves out.
I have also tried the $('#row-img_1').attr(); and I could not get this to work either.
I am aware that I should be using a more effective event handling system but my divs are dynamically generated. Plus this is a small project. ;)
Thanks all for any help.
You need to bind the event function to the element. Setting the event attributes has no effect, as they are interpreted only when the page is loading. Therefore, you need to connect the event callback in a different manner:
$('#row-img_1').mouseover(function() {
alert('foo');
});
$('#row-img_2').mouseout(function() {
alert('foo2');
});
In jQuery, there are two more events: mouseenter and mouseleave. These are similar, but mouseenter does not fire upon moving the mouse from a child element to the main element, whereas mouseover will fire the event again. The same logic applies to mouseleave vs mouseout.
However, jquery provides a shortcut for this kind of usage: the .hover method.
$('#row-img_1').bind('mouseenter', function(event){
// event handler for mouseenter
});
$('#row-img_1').bind('mouseleave', function(event){
// event handler for mouseleave
});
or use jQuerys hover event which effectivly does the same
$('#row-img_1').hover(function(){
// event handler for mouseenter
}, function(){
// event handler for mouseleave
});
Events are registered as functions passed as attributes, like this:
$('#row-img_1').mouseover(function (){ alert('foo'); });
$('#row-img_2').mouseout(function (){ alert('foo2'); });
Also, note the missing on from the onmouseover.
$('#row-img_1').mouseover(function() {
alert('foo');
});

Categories