how to disable MobileSafari auto-selection? - javascript

my webapp requires users to tap and hold on an element for a game action, but iPhone automatically "selects" the area which is confusing to the user.
anyone know what html elements prevent selection, or if javascript can block selection?
any help is appreciated

Try handling the selectstart event and returning false.
Try applying the CSS rule, -webkit-user-select: none;

SLaks answer is obviously right - I just want to extend it a bit for future viewers. If you're using jQuery, here's a useful extension method that disables selection in various browsers:
$.fn.extend({
disableSelection : function() {
this.each(function() {
this.onselectstart = function() { return false; };
this.unselectable = "on";
$(this).css('-moz-user-select', 'none');
$(this).css('-webkit-user-select', 'none');
});
}
});

Related

Stop style HOVER behaviour with jQuery?

I have a div with style.
This style
body .d:hover
{
background-color:red;
}
But I want (if possible) that Jquery will stop this hover behaviour.
I tried with
$(".d").hover(function () { return false;});
$(".d").mouseenter(function () { return false;});
nothing helped.
any help ?
here is the JSBIN ( I want that after pressing the button - nothing will happen when hovering.)
If you want to stop this behavior constantly, you may remove the stylesheet rule, according to W3C wiki:
function stop(m) {
$.each(document.styleSheets, function(i, sheet) {
$.each(sheet.rules, function(i, rule) {
if (new RegExp(m + "\\s*:hover").test(rule.selectorText)) {
sheet.deleteRule(i);
} // TODO: improve RegExp
});
});
}
stop(".d");
If you want to change the state without removing, there is an option to change styleSheet.disabled property, in case you have the :hover rule set in a separate stylesheet.
Note, that I'm not sure about the compatibility issues here, it should be determined additionally.
DEMO: http://jsbin.com/akunew/10/edit
Add a new definition to your CSS:
.d.no-hover:hover {
background-color: black;
}
Now you can just add the no-hover class to the elements which should no longer have a hover effect:
$(obj).addClass('no-hover');
May be this kind of trick: http://jsbin.com/akunew/14/edit
<div style="border:solid 1px red;height:100px;width:100px;" class="d"> </div>
<input type="button" value="stop this hover" onclick="stop()" id="btn"/>
remove the class:
function stop(){
$(".d").addClass('e').removeClass('d');
}
When you calling onclick="stop(this)" it will get input as your $(obj), not your element .d.
EDIT There is no javascript solution to remove :hover
based on ur JSBIN example. below code will work
function stop(obj)
{
$(obj).hover(function () {
$(this).css('background-color','white');
return false;});
$(obj).mouseenter(function () {
$(this).css('background-color','white');
return false;});
$('body').append('<style>body div.d:hover {background-color:transparent !important}</style>');
}
u have overwrite :hover css of that particular element
CSS
.d:hover
{
background-color:Red;
}
.noClass
{
background-color:none;
}
JavaScript
function stop()
{
$(".d").addClass('noClass').removeClass('d');
}
I use a trick- when i am on hover onto an element (and click something inside that HOVERed element), then you can use this javascript method to cancel that hover css:
document.getElementById('sarchevi').className='active';
//on mouse move, remove class
(function(){
var moved = false
window.onmousemove = function(e)
{ if(!moved){ moved = true; document.getElementById('sarchevi').className ='a'; } }
})()
I know this question is four years old, but future visitors should know about the modern approach to this particular problem.
You can use a simple solution that (at its core) uses a CSS property and is supported by all browsers except IE < 11.
$('.d').css('pointer-events', 'none');
You might as well just copy this specific class from Bootstrap:
.disabled {
pointer-events: none;
}
And then apply it via jQuery:
$('.d').addClass('disabled');
Keep in mind, however, that this CSS property prevents the element from capturing any DOM events (such as hover, but also click, etc.)

Enable and disable jquery knob dynamically

I'm using the excellent jQuery knob plugin. However, I need to dynamically enable/disable the element depending on user input. There is support for having a disabled state on page load which have the effect that no mouse (or touch) events are bound to the canvas element. Does anyone know how to resolve this issue, that is, how to (after page load) bind and unbind these mouse event listeners?
Ideally I would like to do something like this (on a disabled knob)
$('.button').click(function() {
$('.knob').enable();
});
Edit:
I ended up rewriting the source which binds/unbinds the mouse and touch events. The solution is not perfect so I leave the question open if someone perhaps have a better (cleaner) solution.
html
<input class="knobSlider" data-readOnly="true">
<button id="testBtn">clickHere</button>
script
in doc ready,
$(".knobSlider").knob();
$("#testBtn").click(function(){
$(".knobSlider").siblings("canvas").remove();
if($(".knobSlider").attr("data-readOnly")=='true'){
$(".knobSlider").unwrap().removeAttr("data-readOnly readonly").data("kontroled","").data("readonly",false).knob();
}
else{
$(".knobSlider").unwrap().attr("data-readOnly",true).data("kontroled","").data("readonly",true).knob();
}
});
For reference you can use my jsfiddle link > http://jsfiddle.net/EG4QM/ (check this in firefox, because of some external resource load problem in chrome)
If someone doesn't like how the accepted answer destroys and recreates the internal canvas element, then checkout my approach:
https://jsfiddle.net/604kj5g5/1/
Essentially, check the draw() implementation (I also recommend listening on value changes in the draw method instead of the change and release, which work for and click and mousewheel events respectively, which imo is inconvenient).
var $input = $("input");
var knobEnabled = true;
var knobPreviousValue = $input.val();
$input.knob({
draw: function () {
if (knobPreviousValue === $input.val()) {
return;
}
if (!knobEnabled) {
$input.val(knobPreviousValue).trigger("change");
return;
}
knobPreviousValue = $input.val();
console.log($input.val());
},
});
Try this to disable the control.
I'm still trying to find a way to enable it back
$("#btnDisable").click(function(){
$("#knob").off().prev().off();
});

how do I know if the mouse pointer is on the HTML element?

I have a timed event I want to behave differently accordingly to what HTML element the mouse pointer is on.
Is there a way, assuming I have the HTML element, to know if the mouse pointer is currently on top of it.
I am well aware of the onmouseover/onmouseout events and how to use them.
I am using JQuery.
I am obviously looking for some kind of flag, as I need to check a state and not handle an event.
again, I know how to implement this with events.
I'm not aware of any built-in way to ping an element for the status of mouse hovering.
However, you can create one by updating a flag at mouseenter and mouseleave -- which is where Brian Driscoll's suggestion of .hover comes in:
jQuery.fn.tracking = function () {
this.data('hovering', false);
this.hover(function () {
$(this).data('hovering', true);
}, function () {
$(this).data('hovering', false);
});
return this;
};
jQuery.fn.hovering = function () {
return this.data('hovering');
}
You'll need to initialize tracking for each element you care about:
$('#elem1,#elem2').tracking();
But then you can get the status of any of them:
if ($('#elem1').hovering()) {
// ...
} else if ($('#elem2').hovering()) {
// ...
}
Demo: http://jsbin.com/amaxu3/edit
Have you looked into jQuery.hover()? http://api.jquery.com/hover/
You need to give name to html andme and on mouseover you need to check document.getelementsbyName. Then check what your are getting as output. Now you can take decision is it html control or asp.net.
When you use collObjects = object.getElementsByName("htmlcontrol") then compare id of both.
1 morething why you needed to check this in javascript. there may be some other solution for that. Just share with us.
You might have some luck with document.elementFromPoint, although I believe there are some inconsistencies in older browser implementations (http://www.quirksmode.org/dom/w3c_cssom.html#documentview).
$('#elem').mousemove(function(e){
if (this == document.elementFromPoint(e.clientX, e.clientY)) {
// Do stuff
}
});
Or outside of a handler
if ($('#elem').get(0) == document.elementFromPoint(x, y)) {
// Do stuff
}
Aside from that, the only other option that comes to mind is using event handlers to keep track of which element the mouse is over.

Chrome sets cursor to text while dragging, why?

My application has many drag and drop features. While dragging I want the cursor to change to some grab cursor. Internet Explorer and Firefox work fine for this, but Chrome always changes the cursor to the text cursor.
None of these solutions worked for me because it's too much code.
I use a custom jQuery implementation to do the drag, and adding this line in the mousedown handler did the trick for me in Chrome.
e.originalEvent.preventDefault();
Try turning off text selection event.
document.onselectstart = function(){ return false; }
This will disable any text selection on the page and it seems that browser starts to show custom cursors.
But remember that text selection will not work at all, so it's the best to do it only while dragging, and turn it on again just after that. Just attach function that doesn't return false:
document.onselectstart = function(){ return true; }
If you want to prevent the browser from selecting text within an element and showing the select cursor, you can do the following:
element.addEventListener("mousedown", function(e) { e.preventDefault(); }, false);
Pitfall
You cannot put the
document.onselectstart = function(){ return false; };
into your "mousedown" handler because onselectstart has already been triggered.
Solution
Thus, to have it working, you need to do it before the mousedown event. I did it in the mouseover event, since as soon as the mouse enters my element, I want it to be draggable, not selectable. Then you can put the
document.onselectstart = null;
call into the mouseout event. However, there's a catch. While dragging, the mouseover/mouseout event might be called. To counter that, in your dragging/mousedown event, set a flag_dragging to true and set it to false when dragging stops (mouseup). The mouseout function can check that flag before setting
document.onselectstart = null;
Example
I know you are not using any library, but here's a jQuery code sample that might help others.
var flag_dragging = false;//counter Chrome dragging/text selection issue
$(".dragme").mouseover(function(){
document.onselectstart = function(){ return false; };
}).mouseout(function(){
if(!flag_dragging){
document.onselectstart = null;
}
});
//make them draggable
$(".dragme").draggable({
start: function(event, ui){
flag_dragging = true;
}, stop: function(event, ui){
flag_dragging = false;
}
});
I solved a same issue by making the Elements not selectable, and adding an active pseudo class on the draged elements:
* {
-webkit-user-select: none;
}
.your-class:active {
cursor: crosshair;
}
I was facing almost same problem. I want cursor inside my DIV element and all its child to be the default, the CSS tips here helped in IE, FF and Opera, but not for Google Chrome. Here is what I have done in parent DIV:
<div ... onselectstart="return false;" ... > ... </div>
Now it is working fine. Hope this help.
I have a similar issue using jQuery UI draggable and sortable (ver. 1.8.1), and it's quite specific, so I assume that you are using same library.
Problem is caused by a bug in jQuery UI (actually a fix for other Safari bug).
I just raised the issue in jQuery UI http://dev.jqueryui.com/ticket/5678 so I guess you will need to wait till it's fixed.
I've found a workaround for this, but it's quite hard-core, so you only use it if you really know what is going on ;)
if ($.browser.safari) {
$.ui.mouse.prototype.__mouseDown = $.ui.mouse.prototype._mouseDown;
$.ui.mouse.prototype._mouseDown = function(event){
event.preventDefault();
return $.ui.mouse.prototype.__mouseDown.apply(this, arguments);
}
}
It simply switches off the fix that's in jQuery UI code, so basically it may break something.
Just use this line inside your mousedown event
arguments[0].preventDefault();
You can also disable text selection by CSS adding this class to your draggable element
.nonselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

Disable Drag and Drop on HTML elements?

I'm working on a web application for which I'm attempting to implement a full featured windowing system. Right now it's going very well, I'm only running into one minor issue. Sometimes when I go to drag a part of my application (most often the corner div of my window, which is supposed to trigger a resize operation) the web browser gets clever and thinks I mean to drag and drop something. End result, my action gets put on hold while the browser does its drag and drop thing.
Is there an easy way to disable the browser's drag and drop? I'd ideally like to be able to turn it off while the user is clicking on certain elements, but re-enable it so that users can still use their browser's normal functionality on the contents of my windows. I'm using jQuery, and although I wasn't able to find it browsing the docs, if you know a pure jQuery solution it would be excellent.
In short: I need to disable browser text selection and drag-and-drop functions while my user has the mouse button down, and restore that functionality when the user releases the mouse.
This works. Try it.
<BODY ondragstart="return false;" ondrop="return false;">
Try preventing default on mousedown event:
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
or
<div onmousedown="return false">asd</div>
You can disable dragging simply by using draggable="false" attribute.
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable
http://www.w3schools.com/tags/att_global_draggable.asp
This might work: You can disable selecting with css3 for text, image and basically everything.
.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
Of course only for the newer browsers. For more details check:
How to disable text selection highlighting
Note: there are obvious a few UX downsides to this since it prevents users from easily copying text, be aware of this.
With jQuery it will be something like that:
$(document).ready(function() {
$('#yourDiv').on('mousedown', function(e) {
e.preventDefault();
});
});
In my case I wanted to disable the user from drop text in the inputs so I used "drop" instead "mousedown".
$(document).ready(function() {
$('input').on('drop', function(event) {
event.preventDefault();
});
});
Instead event.preventDefault() you can return false. Here's the difference.
And the code:
$(document).ready(function() {
$('input').on('drop', function() {
return false;
});
});
This is a fiddle I always use with my Web applications:
$('body').on('dragstart drop', function(e){
e.preventDefault();
return false;
});
It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.
try this
$('#id').on('mousedown', function(event){
event.preventDefault();
}
For input elements, this answer works for me.
I implemented it on a custom input component in Angular 4, but I think it could be implemented with pure JS.
HTML
<input type="text" [(ngModel)]="value" (ondragenter)="disableEvent($event)"
(dragover)="disableEvent($event)" (ondrop)="disableEvent($event)"/>
Component definition (JS):
export class CustomInputComponent {
//component construction and attribute definitions
disableEvent(event) {
event.preventDefault();
return false;
}
}
using #SyntaxError's answer, https://stackoverflow.com/a/13745199/5134043
I've managed to do this in React; the only way I could figure out was to attach the ondragstart and ondrop methods to a ref, like so:
const panelManagerBody = React.createRef<HTMLDivElement>();
useEffect(() => {
if (panelManagerBody.current) {
panelManagerBody.current.ondragstart = () => false;
panelManagerBody.current.ondrop = () => false;
}
}, [panelManagerBody]);
return (
<div ref={panelManagerBody}>
I will just leave it here. Helped me after I tried everything.
$(document.body).bind("dragover", function(e) {
e.preventDefault();
return false;
});
$(document.body).bind("drop", function(e){
e.preventDefault();
return false;
});
Question is old, but it's never too late to answer.
$(document).ready(function() {
//prevent drag and drop
const yourInput = document.getElementById('inputid');
yourInput.ondrop = e => e.preventDefault();
//prevent paste
const Input = document.getElementById('inputid');
Input.onpaste = e => e.preventDefault();
});
You can simply use draggable="false" on the element itself, else you can put
on-mousedown="preventDefaultDrag"
...
preventDefaultDrag: function(ev) {
ev.preventDefault();
},
This JQuery Worked for me :-
$(document).ready(function() {
$('#con_image').on('mousedown', function(e) {
e.preventDefault();
});
});

Categories

Resources