I made the following script to override the browsers' default outlining system:
*
{
margin: 0;
outline-color: #C79700;
outline-width: 1px;
padding: 0;
}
$('document').delegate('[tabindex]', 'focusin focusout mousedown', function(event)
{
var target = $(event.target);
switch(event.type)
{
case 'focusin':
{
var clicked = target.data('clicked');
target.removeData('clicked');
if (clicked)
target.css('outline-style', 'none');
else
target.css('outline-style', 'solid');
break;
}
case 'focusout':
target.css('outline-style', 'none');
break;
case 'mousedown':
{
if (target.prop('tagName') === 'B')
target = target.parent();
if (!target.is(':focus'))
target.data('clicked', true);
else
target.css('outline-style', 'none');
break;
}
}
})
Everything works perfectly but I have a minor issue: if I activate another window (by minimizing the browser or using ALT+TAB), the document loses the focus and so does the element... then, if I reactivate the browser window, data('clicked') is obviously false and if a [tabindex] element is selected, it is outlined by the script.
How can I prevent this? I've tried a lot of solutions without success. Is there something like:
if (clicked || browser-has-just-become-active)
target.css('outline-style', 'none');
else
target.css('outline-style', 'solid');
Many many thanks!
I'm pretty sure you can use:
window.onfocus
or for IE:
document.onfocusin
Related
I need someone to head me to the right direction (I've done mostly back-end stuff and recently my JS experience has involved mostly jQuery, not too many low-level programming in JS, so I'm lacking the JS patterns on how to implement it properly).
https://jsfiddle.net/honesta/4jef9k29/6/
// Keydown
$(this).on('keydown', function(event) {
switch(event.keyCode) {
case 27: // escape
this.hide();
break;
// case 40: // keydown
//
default:
this.request();
break;
}
});
I have this custom autocomplete, trying to make the keyboard KEYUP and KEYDOWN working to navigate the list. Any idea where do I start? What would be the best approach? Or some similar example where I can base my implementation.
It will be a bit complicated because of the bootstrap :hover state on dropdown items.
$(this).on('keydown', function(event){
switch(event.keyCode) {
case 27: // escape
this.hide();
break;
case 40: //Keydown
event.preventDefault();
var active_li = $('.li_active').removeClass('li_active').next();
if(!active_li.length) active_li = $('ul.dropdown-menu li:eq(0)');
active_li.addClass('li_active').find('a').trigger('mouseenter');
break;
case 38: //Keyup
event.preventDefault();
var active_li = $('.li_active').removeClass('li_active').prev();
if(!active_li.length) active_li = $('ul.dropdown-menu li:last-child');
active_li.addClass('li_active').find('a').trigger('mouseenter');
break;
case 13:
var value = $('ul.dropdown-menu .li_active').removeClass('li_active').attr('data-value');
if (value && this.items[value]) {
this.select(this.items[value]);
this.hide();
}
break;
default:
this.request();
break;
}
});
To not interfere with the bootstrap :hover state, you will need to override CSS and add event handlers:
$(this).siblings('ul.dropdown-menu')
.on('click', 'a', $.proxy(this.click, this))
.on('mouseenter', 'a', function(){
$('.li_active').removeClass('li_active');
$(this).parent().addClass('li_active');
})
.on('mouseleave', 'a', function(){
$('.li_active').removeClass('li_active');
});
CSS:
ul.dropdown-menu li a:hover{
background : #ffffff;
}
ul.dropdown-menu .li_active, ul.dropdown-menu .li_active a:hover {
background : #f5f5f5;
}
JSFiddle demo
I am building a game
And I need to do something when the user clicks on the right mouse button, holds it and then presses the left button
How can I detect this behaviour?
JSfiddle: https://jsfiddle.net/mkarajohn/pd725ch6/5/
var rightMouseClicked = false;
function handleMouseDown(e) {
//e.button describes the mouse button that was clicked
// 0 is left, 1 is middle, 2 is right
if (e.button === 2) {
rightMouseClicked = true;
} else if (e.button === 0) {
//Do something if left button was clicked and right button is still pressed
if (rightMouseClicked) {
console.log('hello');
//code
}
}
console.log(rightMouseClicked);
}
function handleMouseUp(e) {
if (e.button === 2) {
rightMouseClicked = false;
}
console.log(rightMouseClicked);
}
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
Use MouseEvent.buttons in your event handler.
<element>.addEventListener("mousedown", function(event){
if ((event.buttons & 3) === 3){
//Do something here
}
}, true);
It is kinda recent though, you may want to implement fallback method, recording state of mouse buttons.
You can try this one.
window.oncontextmenu = function () {
showCustomMenu();
return false; // cancel default menu
}
on right click every browser has default menu for refreshing page, printing, saving and lot more but you can try this one and may be it will prevent default action and add your custom.
please write down answer if it will help you.
for right click use oncontextmenu and for left just set up click , just disable their default behaviours if you want too,
ex:
var left = 0,
right = 0;
document.onclick = function() {
console.log(++left);
return false;
};
document.oncontextmenu = function() {
console.log(++right);
return false;
};
Hie
check below code
<!doctype html>
<html lang="en">
<head>
<input type='button' value='Click Me!!!' id='btnClick'/>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$('#btnClick').mousedown(function(event){
switch (event.which) {
case 1:
alert('Left mouse button pressed');
break;
case 2:
alert('Middle mouse button pressed');
break;
case 3:
alert('Right mouse button pressed');
break;
default:
break;
}
});
});
</script>
</body>
</html>
For more reference refer
http://www.jquerybyexample.net/2011/04/find-which-mouse-button-clicked-using.html
Try
var hold=false;
function check(e) {
if(e.button==2) hold=true;
if(e.button==0 && hold) console.log('action');
}
function release(e) {
if(e.button==2) hold=false;
}
function noContext(e) { e.preventDefault(); }
.box { width: 100px; height: 100px; border: 1px solid black;}
Hold right mouse button and press left (on sqare)
<div class="box"
onmousedown="check(event)"
onmouseup="release(event)"
oncontextmenu="noContext(event)"
></div>
I am trying to build a minesweeper game with php and jquery. This means I want the user to be able to right-click elements to mark areas as a potential bomb or a questionmark. Now I have the right click event and the code works, however if I don't alert anything I get the menu with inspect element etc. I've tried throwing in some return false's but they haven't helped. How can I stop the menu appearing on right-click?
$('.overlay').mousedown(function(event) {
switch (event.which) {
case 1:
//left click code
break;
case 3:
theID = event.target.id;
if ($('#'+theID).is(":visible") && $('.bomb_'+theID).css("visibility") == "hidden"
&& $('.mystery_'+theID).css("visibility") == "hidden"){
$('#'+theID).css("background", "none");
$('.bomb_'+theID).css("visibility", "visible");
alert("x");
}else if($('.bomb_'+theID).is(":visible")){
$('.bomb_'+theID).css("visibility", "hidden");
$('.mystery_'+theID).css("visibility", "visible");
alert("y");
}else{
$('.mystery_'+theID).css("visibility", "hidden");
$('#'+theID).css("background", "#fff");
alert("z");
}
break;
}
});
Have tried to add event.preventDefault(); under the mousedown function but this doesn't change anything. Also tried it under case 3:.
Also return false; and event.stopImmediatePropagation(); don't work.
Have you tried this via the context menu event?
$(".overlay").on("contextmenu",function(e){
....
e.stopImmediatePropagation();
e.preventDefault();
return false;
});
You might want to try event.preventDefault();
Any insights on how to catch a scrolling event on a element that has overflow:hidden? I would like to scroll in a column without showing a scrollbar to the user.
This is actually a somewhat indepth process. What I do is set global flags when users mouse enters and leaves the element that you want to scroll. Then, on the mousewheel event for the body I check to see if the MOUSE_OVER flag is true, then stop propagation of the event. This is so the main body doesnt scroll in case your entire page has overflow.
Note that with overflow hidden, the default scrolling ability is lost so you must create it yourself. To do this you can set a mousewheel listener on your div in question and use the event.wheelDelta property to check whether the user is scrolling up or down. This value is different according to browser, but it is generally negative if scrolling down and positive if scrolling up. You can then change position of your div accordingly.
This code is hacked up quickly but it would essentially look like this...
var MOUSE_OVER = false;
$('body').bind('mousewheel', function(e){
if(MOUSE_OVER){
if(e.preventDefault) { e.preventDefault(); }
e.returnValue = false;
return false;
}
});
$('#myDiv').mouseenter(function(){ MOUSE_OVER=true; });
$('#myDiv').mouseleave(function(){ MOUSE_OVER=false; });
$('#myDiv').bind('mousewheel', function(e){
var delta = e.wheelDelta;
if(delta > 0){
//go up
}
else{
//go down
}
});
I use overflow:scroll, but also Absolutely position a div over the scroll bar in order to hide it.
$("body").css("overflow", "hidden")
$(document).bind('mousewheel', function(evt) {
var delta = evt.originalEvent.wheelDelta
console.log(delta)
})
works for me. adapted from How do I get the wheelDelta property?
I edited #anson s answer to Vanilla Javascript since it may be useful for others. Also note that "mousewheel" event is deprecated. So my code uses "wheel" instead. Next to that I added arrow functions for practical access the to "this".
fixScrollBehavior(elem) {
elem.addEventListener('scroll', (e) => {
console.log('scrolling');
});
let MOUSE_OVER = false;
elem.addEventListener('wheel', (e) => {
if (MOUSE_OVER) {
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
return false;
}
});
elem.addEventListener('mouseenter', () => {
MOUSE_OVER = true;
});
elem.addEventListener('mouseleave', () => {
MOUSE_OVER = false;
});
elem.addEventListener('wheel', (e) => {
let delta = e.wheelDelta;
if (delta > 0) {
//go up
} else {
//go down
}
});
}
Note that this does not fix the mobile touch-"scroll"s.
$("div").on('wheel', function (e) {
if (e.originalEvent.deltaY < 0) {
console.log("Scroll up");
} else {
console.log("Scroll down");
}
});
This did the trick for me.
JSFiddle
StackFiddle:
$("div").on('wheel', function(e) {
if (e.originalEvent.deltaY < 0) {
console.log("Scroll up");
} else {
console.log("Scroll down");
}
});
div {
height: 50px;
width: 300px;
background-color: black;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
I am late, but I think I have a better answer.
Style your container as overflow: overlay, this will free up space of scrollbar, then style scrollbar or hide it or make its handle height/width 0,
Then you should get scroll events also.
Note : styling the scrollbar is not supported in all web browsers.
When double-clicking on a html page most browsers select the word you double-click on (or the paragraph you triple-click on). Is there a way to get rid of this behavior?
Note that I do not want to disable regular selection via single-click+dragging; i.e. jQuery UI's $('body').disableSelection() and the document.onselectstart DOM event are not what I want.
I fear you can't prevent the selection itself being "native behavior" of the browser, but you can clear the selection right after it's made:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
Edit: to also prevent selecting whole paragraph by "triple click", here is the required code:
var _tripleClickTimer = 0;
var _mouseDown = false;
document.onmousedown = function() {
_mouseDown = true;
};
document.onmouseup = function() {
_mouseDown = false;
};
document.ondblclick = function DoubleClick(evt) {
ClearSelection();
window.clearTimeout(_tripleClickTimer);
//handle triple click selecting whole paragraph
document.onclick = function() {
ClearSelection();
};
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
};
function RemoveDocumentClick() {
if (!_mouseDown) {
document.onclick = null;
return true;
}
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
return false;
}
function ClearSelection() {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
Live test case.
Should be cross browser, please report any browser where it's not working.
The following works for me in the current Chrome (v56), Firefox (v51) and MS Edge (v38) browsers.
var test = document.getElementById('test');
test.addEventListener('mousedown', function(e){
if (e.detail > 1){
e.preventDefault();
}
});
<p id="test">This is a test area</p>
The MouseEvent.detail property keeps track of the current click count which can be used to determine whether the event is a double, tripple, or more click.
Internet explorer unfortunately does not reset the counter after a timeout period so instead of getting a count of burst-clicks you get a count of how many times the user has clicked since the page was loaded.
Just put this on the css interested section
-moz-user-select : none;
-khtml-user-select : none;
-webkit-user-select : none;
-o-user-select : none;
user-select : none;
If you really want to disable selection on double-click and not just remove the selection afterwards (looks ugly to me), you need to return false in the second mousedown event (ondblclick won't work because the selection is made onmousedown).
**If somebody wants no selection at all, the best solution is to use CSS user-select : none; like Maurizio Battaghini proposed.
// set to true if you want to disable also the triple click event
// works in Chrome, always disabled in IE11
var disable_triple_click = true;
// set a global var to save the timestamp of the last mousedown
var down = new Date().getTime();
var old_down = down;
jQuery(document).ready(function($)
{
$('#demo').on('mousedown', function(e)
{
var time = new Date().getTime();
if((time - down) < 500 &&
(disable_triple_click || (down - old_down) > 500))
{
old_down = down;
down = time;
e.preventDefault(); // just in case
return false; // mandatory
}
old_down = down;
down = time;
});
});
Live demo here
Important notice: I set the sensitivity to 500ms but 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. - api.jquery.com
Tested in Chrome and IE11.
Just to throw this out there, but here's the code I slap into my pages where I expect users to be clicking rapidly. However, this will also disable standard click-n-drag text selection.
document.body.onselectstart = function() {
return false;
}
document.body.style.MozUserSelect = "none";
if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
document.body.onmousedown = function() {
return false;
}
}
Seems to work well for me.