prevent previously defined events on mousedown for right-click only - javascript

I have a soundboard with buttons that trigger AJAX posts on mousedown.
The ideal functionality is to play an audio on left-mousedown and cancel playback on right-mousedown.
The code I have so far disables the context menu and cancels the playback...however, if they are over a button when they right-click (that triggers other previously defined events), it will still honor the mousedown and play that audio.
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
$(document).mousedown(function(e){
if( e.which == 3 ) {
e.preventDefault();
Cancel_Playback();
return false;
}
return true;
});
});
I am trying to disable the right-mousedown from triggering the previously defined events but honor the Cancel_Playback. Any ideas?
EDIT
Updated Title and Description to more accurately reflect what I am trying to accomplish. This should also help: http://jsfiddle.net/g9sh1dme/15/

stopImmediatePropagation is probably the function you're looking for.
It cancels all other events bound to the the same element and any other delegates higher in the DOM. Order also matters as events are called in the order in which they were bound. You can only cancel events that were bound after the event doing the canceling.
I'm not sure if these changes maintain the validity of your program, but it demonstrates the function's use. Otherwise, I'd just check for right-mousedown in Play_Sound and exit out instead of banking on another event to cancel its execution.
Live Demo
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
//For this to work you must bind to the same object or you must bind to something lower in the DOM.
$(".sound").mousedown(function(e){
if( event.which == 3 ) {
Cancel_Playback();
e.stopImmediatePropagation();
return false;
}
return true;
}).mousedown(Play_Sound);
})
function Cancel_Playback() {
alert("This is all that should be displayed on right-mousedown")
}
function Play_Sound() {
alert("Display this on left-mousedown... but not on right-mousedown")
}

Related

Prevent tab key from selecting URL in Javascript/Jquery

I'm making a game, and there's a leaderboard. I want the user to be able to toggle the leaderboard by hitting the TAB key. Here is my code:
keysPressed = {};
if(keysPressed[KEY_TAB]){
if(leaderboard.style.display == 'none'){
$(leaderboard).fadeIn(100);
} else {
$(leaderboard).fadeOut(100);
}
keysPressed[KEY_TAB] = false;
}
document.addEventListener('keydown', (event) => {
keysPressed[event.key.toLowerCase()] = true;
}, false);
document.addEventListener('keyup', (event) => {
keysPressed[event.key.toLowerCase()] = false;
}, false);
Note: leaderboard is just document.getElementById('leaderboard')
This all works fine, but whenever I hit the tab key, the webpage (I'm using Chrome) automatically selects/deselects the URL bar. Is there a way I can prevent the TAB key from doing this, or do I need to switch to a different key? Here is an screenshot demonstrating my problem:
JavaScript is prefered, since I am rather new to jQuery, but I am willing to go either.
Thanks in advance~
Use Event.preventDefault()
From MDN :
The preventDefault() method of the Event interface tells the user
agent that if the event does not get explicitly handled, its default
action should not be taken as it normally would be.
The event continues to propagate as usual, unless one of its event
listeners calls stopPropagation() or stopImmediatePropagation(),
either of which terminates propagation at once.
As noted below, calling preventDefault() for a non-cancelable event,
such as one dispatched via EventTarget.dispatchEvent(), without
specifying cancelable: true has no effect.
document.addEventListener('keydown', (event) => {
if (event.key == "Tab") {
event.preventDefault();
}
}, false);

Stop Click callback when double clicked on node in Fancytree

I want to the control to not go into Click callback when Double click on the node in fancytree
This is standard browser behavior, Fancytree does not do anything special about the click events.
However: from jQuery help (http://api.jquery.com/dblclick/):
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
See also https://github.com/mar10/fancytree/issues/578
You're giving very little to work with, so I'll give you a general double click implementation example.
HTML
<input type="button" id="yourControl">
JS
var waitingForSecondClick = false;
$(document).ready(function() {
$('#yourControl').click(function() {
if (waitingForSecondClick) {
waitingForSecondClick = false;
onDoubleClick();
} else {
waitingForSecondClick = true;
setTimeout(function() { waitingForSecondClick = false}, 300);
}
return false;
});
function onDoubleClick() {
alert('Double clicked!');
}
});
Check this fiddle

Double event handler and one function. How to prevent executing code twice?

I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.
This is the example code:
$(document).on('focusout change', '.selector', function() {
if ($(this).is(':checkbox')) {
// Do stuff and prevent the focusout to trigger. HOW???
}
doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});
The code above will execute twice:
When the checkbox gets checked/unchecked
When you click outside of the checkbox (lose focus (blur))
I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.
What would be the way to prevent the focusout handler to trigger for certain elements?
What you want to do is
$(document).on('focusout change', '.selector', function(event) {
event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate
The best way is to affect both events (or more) to the same function, like this :
A text input for example
<input id="myfield" type="text" />
Now the Javascript
var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
//your code
}
Yo can even add an other element
button.onclick = myfield.onkeyup = function(e)
{
//when the client press the enter key
if(e.key && e.key == "Enter")
{
//catch the target
}
//when the client click the button
else if(!e.key || e.target == button)
{
//catch the target
}
//otherwise you can do not care about the target and just execute your function
}
You must only know that you can add many elements and many events
element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}

Input with clear icon - loss of focus issue

I have a clearable input like this:
+-----------------+
| x |
+-----------------+
The clear icon is a span with a font glyph in the :before:
<wrapper>
<input>
<icon span>
</wrapper>
Validation of inputs is done on blur (which re-renders the input View for validation message and icon changes - this keeps the architecture simple). The issue I am experiencing is that by clicking the icon the input triggers a blur and then the icon click.
Can you think of a way to either:
a) Avoid triggering a blur -- I can only think of ditching font glyph and using a background image, but I am already using other glyphs for required, invalid etc in that position so it is undesired
b) Detecting that the blur was caused by the icon and not something else
Thanks.
Edit: Here is one idea, a bit lame using a setTimeout though: http://jsfiddle.net/ferahl/td5VR/
Consider using mousedown and mouseup events to set/remove a flag.
http://jsfiddle.net/td5VR/4/
var wasClicked = false;
$('input').blur(function(){
$(".results").text(wasClicked ? "was clicked": "wasn't clicked");
});
$('.something').mousedown(function(){
wasClicked = true;
}).mouseup(function() {
wasClicked = false;
});
Though you still need to disable keyboard navigation to the link by setting tabindex="-1".
Here's a few ideas of what might be happening and some approaches to try:
This is a guess, but perhaps what you're experiencing is something called event bubbling. Take a look at this page to learn more about it. You can prevent event bubbling in your click handler like this:
IconElement.onclick = function(event) {
event = event || window.event // cross-browser event
if (event.stopPropagation) {
// W3C standard variant
event.stopPropagation()
} else {
// IE variant
event.cancelBubble = true
}
}
(If you're using jQuery, you don't need to worry about the "IE variant")
You could also try adding return false; or event.preventDefault() and see if that works.
And one more approach is to check event.target in your blur handler:
InputElement.onblur = function(event) {
event = event || window.event // cross-browser event
var IconElement = [do something to get the element];
if (event.target == IconElement) {
// Ignore this blur event, or maybe even call "this.focus()"
}
}
Here is the final very simple solution inspired by #Yury's answer:
$('.clearable-icon').mousedown(function() {
// This happens before blur, so return false and stop propagation.
return false;
});

disable button in a <li>

okay, if I have six buttons in a list, under the li tag (each on is rel to a part of an array), how can I disable a button while it's doing it's thing? (In this case playing a video)I know it's a little vague (i haven't supplied code or anything of the sort), but that's because I don't know how to go about it. If I could at least get pointed in the right direction, that would be helpful, so that even if I can't figure it out, at least I can be specific with my problem... thanks...EDIT this is what I've now done
<li rel='1' id="first">
<div style="top:0px;">
<img src="graphics/filler.png" alt="" width="280" height="128" onClick="asess"/>
</div>
</li>
and then added the corresponding function
function asess() {
document.getElementById("first").disabled = true;
}
I'm not to concerned with adding the function back just yet, because first I'd like to make this part work.EDIT I've got this, which should work, but I guess it's not "talking" to the button?
$("li, .thumbs").bind("touchstart click", function() {
var $this = $(this);
if (!document.getElementById("first").disabled) {
document.getElementById("first").disabled = true }
else {document.getElementById("first").disabled = false};
});
I know it will only talk to the button with that id (first one) but as long as I can make it work for one, I can do the rest. So, what am I doing wrong?
Each button will have an onclick event handler. To prevent the onclick handler from doing anything the JavaScript method attached to the handler should return false. If you are doing this with jQuery return false; is the same as calling e.preventDefault (or event.preventDefault for IE).
When the normal event handler initiates the action associated with the button it should add the event handler that disables the onclick action.
You will probably need to apply a new CSS style to the button as well so the user knows it's disabled.
When the action completes you need to remove event handler that disables the onclick action and use the normal one again.
You could always just use a flag to say an action is in progress and set this on and off with the actions. If the flag is on then the event handler method returns false.
By using the event handler you could also show an alert to the user when they try and click the button before you return false.
EDIT:
Here is the sort of JavaScript you'll need, the first click starts the process which will stop itself after five seconds using setTimeout('stopAction()', 5000);. If you click the item again during that time you get the wait message.
I would recommend you look at using jQuery to develop a robust cross browser solution.
var inProgress = false;
function asess() {
if(inProgress) {
alert('Please wait ...');
return false;
} else {
startAction();
}
}
function startAction() {
inProgress = true;
alert('Starting');
document.getElementById("first").style.backgroundColor = '#333333';
setTimeout('stopAction()', 5000);
}
function stopAction() {
inProgress = false;
alert('Stopping');
document.getElementById("first").style.backgroundColor = '#FFFFFF';
}
document.getElementById("my_button").disabled = true;
and when you're done.
document.getElementById("my_button").disabled = false;
You could "disable" the element within the click handler and re-enable it when the callback is executed successfully.
Click handler binding to elements with disabled="disabled" attribute is not guaranteed to be consistently implemented across browsers (i.e. the event could/would still fire) and is not allowed except on form elements anyway. I'd just add class="disabled" which gives me additional powers to style the disabled element state by, say, greying it out.
Oh, and jQuery. Naturally, this logic could be reproduced in "normal" javascript but is so tidier with library usage, fiddle:
$('#my-button').click(function() {
var $this = $(this); //cache the reference
if (!$this.hasClass('disabled')) {
$this.addClass('disabled');
alert('hello world!');
setTimeout(function($btn) {
$btn.removeClass('disabled');
}, 5000, $this);
} else {
return false;
}
});

Categories

Resources