I have script that triggers on hover and on click events on specific tag
$(".dropdown-button").dropdown({
hover: true, // Activate on hover
});
Unfortunately, triggering onclick event is set by default.
How Can i forbid triggering script on click event? I need it to be triggered only on hover.
I need it only in this particular case for this specific tag .dropdown-button.
update
I use materializecss http://materializecss.com/dropdown.html
.off() disables onhover event, but not click.
To forbid triggering script on click event it would be good if you overwrite the click event. You can bind this click event with a empty function.
You probably can do this
var hoverTimer;
var hoverDelay = 200;
$('.dropdown-button').hover(function() {
var $target = $(this);
// on mouse in, start a timeout
hoverTimer = setTimeout(function() {
// do your stuff here
$target.trigger('click');
}, hoverDelay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(hoverTimer);
});
Related
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;
});
I have a drag-drop-application which uses JQuery UI onDrag and onDrop. This application is a room reservation system that have tabs. I have made the drop-working perfectly, but there is one functionality I really want (if possible).
Is there a way to create a event-handler for the tabs, that fires only if you are dragging an element?
Example: You want to move a person from Tab1 to Tab2, without clicking the tab, you can only drag the person -> hover the tab -> then the tab gets clicked.
There is no specific event handler for dragging an element, but by manipulating other events, you can make it work.
The trick is to use the mousemove event, but make it only work when the mouse has been pressed down on the draggable element. Therefore, we make a certain Boolean true in the mousedown event and then make it false in the mouseup event. The mousemove event checks if the Boolean and runs its code if and only if the Boolean is true.
Here's an example:
$(document).ready(function() {
//Make draggable draggable
$("#draggable").draggable();
//mousedown and mouseup Boolean
var drragging = false;
$("#draggable").mousedown(function() { dragging = true; });
$("#draggable").mouseup(function() { dragging = false; });
//mousemove event -> mousedrag event
$("#draggable").mousemove(function() { if (dragging) {
//The event:
$("#draggable").css("color", "rgb("+Math.round(255*Math.random())+", "+Math.round(255*Math.random())+", "+Math.round(255*Math.random())+")");
}});
});
<span id="draggable">Drag me!</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
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)
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
I want to have a loader attached on my buttons on mousedown on every page.
I have a function that fires after the layout renders and passes in the top level view, then grabs every button and attaches a mousedown event on it :
attachGlobalButtonEventHandler : function(view){
view.$el.find('button.viewtag, button.newtag').on('mousedown', function(){
var $target = $(this);
$target.addClass('activated');
$target.prop('disabled', true);
});
}
This works fine, but the problem is my backbone events on the buttons are not getting fired, which looks like:
events : {
'click .newtag' : 'gotoCreate'
},
gotoCreate : function(evt) {
evt.preventDefault();
app.router.navigate('somewhere', true);
}
If I remove the attachGlobalButtonEventHandler, then the click on newtag fires fine, but does not fire at all if the handler is attached. How can I make sure the backbone click event will fire as well?
The problem here is the disabled property and the order events are executed.
The mousedown event happens before the click event and in the mousedown callback you disable the button, thus removing the click event entirely.
Check this jsFiddle out. If you comment out the line $(this).prop('disabled', true); then the click event will fire.
By adding a setTimeout you can effectively execute it on the next tick, see this jsFiddle for details.
Edit: I just noticed #codemonkey had added a comment suggesting the same thing.