Cancel Drag & Selection event - javascript

I'm using this function that I found in Chrome Resources Files (chrome://resources/js/util.js) and is working well on Google Chrome.
/**
* Disables text selection and dragging.
*/
function disableTextSelectAndDrag() {
// Disable text selection.
document.onselectstart = function(e) {
e.preventDefault();
}
// Disable dragging.
document.ondragstart = function(e) {
e.preventDefault();
}
}
I want to cancel this events in Internet Explorer 8 but this doesn't work on it.
How can I cancel this events in IE8 ?

Try this:
/**
* Disables text selection and dragging on IE8 and below.
*/
function disableTextSelectAndDragIE8() {
// Disable text selection.
document.body.onselectstart = function() {
return false;
}
// Disable dragging.
document.body.ondragstart = function() {
return false;
}
}

Related

How do I prevent the user from typing new lines in a contentEditable element?

I made my div element contentEditable so that the user can edit its contents:
<div contentEditable='true' id='myDiv'>
This content can be edited.
</div>
However, I'd like to prevent the user from typing new lines into the div element. I've tried preventing the default action of keydown events to no avail:
var container = document.getElementById('myDiv');
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
container.blur();
e.preventDefault();
return false;
}
return true;
}
myDiv.addEventListener(
'keydown', tryToPreventNewLines);
myDiv.addEventListener(
'change', tryToPreventNewLines);
JSFiddle: http://jsfiddle.net/pwmspdm4/
In this case, the user can produce several new lines by hitting the enter key while within the div and not letting go of the enter key.
The problem seems to be the container.blur() call; if you move that out of the handling of the event with a setTimeout, the code works (prevents the user creating a newline, and blurs the container):
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
e.preventDefault();
setTimeout(function() {
container.blur();
}, 0);
return false;
}
return true;
}
Updated Fiddle
Of course, I'm assuming you want to blur the container when they press Enter. If not, just remove that line entirely.
Tested on Chrome, Firefox, and IE11.
Below you note that on Chrome, holding down Enter continues to add newlines, even with the above. The only way I see to prevent that is to control the contentEditable property:
var container = document.getElementById('myDiv');
function tryToPreventNewLines(e) {
switch (e.keyCode) {
case 13:
e.preventDefault();
this.contentEditable = false; // No longer editable
this.blur(); // Remove selection box on Firefox
return false;
}
// Removed the `return true;` here; it was a no-op
}
function enableEdit() {
this.contentEditable = true; // Make it editable
this.focus(); // And put the cursor in it
}
// Just for max compatibility, added the third argument below;
// some browsers still require it
myDiv.addEventListener(
'keydown', tryToPreventNewLines, false);
myDiv.addEventListener(
'change', tryToPreventNewLines, false);
myDiv.addEventListener(
'click', enableEdit, false);
Updated Fiddle

Check for Touch device with Javascript

I have 3 buttons with hover states which makes a little tooltip appear to describe the button. They work fine but on touchs screen they do not disappear after the user clicks on the button.
So I've tried a few js scripts for checking if a device is a touch device or not. They almost work but they also when I test on IE11 it also gets detected as a touch device. Chrome & Firefox do not get mistaken as a touch device.
Any sugestions?
Her is what I've tried
/*****************************
TOUCH DEVICES HOVER FIX START
****************************/
// http://stackoverflow.com/a/4819886/1814446
function isTouchDevice() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
};
// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/#poke-it
var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
hasTouch = true;
// Remove event listener once fired, otherwise it'll kill scrolling
// performance
window.removeEventListener('touchstart', setHasTouch);
}, false);
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
define(['Modernizr', 'prefixes', 'testStyles'], function( Modernizr, prefixes, testStyles ) {
// Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
Modernizr.addTest('touchevents', function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['#media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
});
});
if(bool===true) {
console.log('Touch Device'); //your logic for touch device
jQ( "#btn-1, #btn-2, #btn-3" ).click(function() {
jQ("#btn-1 .tooltip").css('opacity', '0');
jQ("#btn-2 .tooltip").css('opacity', '0');
jQ("#btn-3 .tooltip").css('opacity', '0');
});
}
else {
//your logic for non touch device
}
For IE10+ you can utilize "window.navigator.msMaxTouchPoints"
example code
function isIETouch ()
{
return window.navigator.msMaxTouchPoints == undefined ? false : window.navigator.msMaxTouchPoints;
}

A confirmation popup in JS

I am looking into making a confirmation menu in JavaScript to where it will run a set of code depending if you select yes or no.
Now I want it to happen on the window.onbeforeunload event but only when the individual presses "yes" do I want the rest of the code to work. If they press "no" I want the window.onbeforeunload to be cancelled outright. I am wondering if it is at all possible and how. Here is what I have so far. The reason why I want this is because when I run the script the popup shows up on return but before someone would get to choose to stay or leave. The click(); feature starts up erasing the information. I want the .click(); to start up after someone presses "yes" on the return and only if they press "yes".
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = document.getElementById("kioskform:broswerCloseSubmit");
var leave_safari = document.getElementById("kioskform:broswerCloseSafari");
function goodbye(e) {
if (!validNavigation) {
function disp_confirm()
{
var leaveMessage=confirm("Are you sure you want to leave")
if (leaveMessage==true)
{ if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//for IE
e.cancelBubble = true;
e.returnValue = leave_message.click();
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
leave_safari.click();
return '';
//add the code to delete the kiosk information here.
// this is what is to be done.
}
}
else
{
Alert("Returning to the page.")
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
jQuery('document').bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
jQuery("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
jQuery("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
jQuery("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function() {
wireUpEvents();
});
Why not just use window.confirm?

Cross-browser enabling/disabling mouse scroll wheel

I have 2 button: "disable_scroll" and "enable_scroll" for enabling/disabling mouse scroll.
Disabling scroll works well:
var cancelscroll = function(e) {
e.preventDefault();
};
$("#disable_scroll").on("click", function () {
if ("onmousewheel" in document) { // for browser except FF
document.onmousewheel = cancelscroll;
} else { // for FF
document.addEventListener('DOMMouseScroll', cancelscroll);
}
});
but when I want to enable mouse scroll, I have problems in Firefox. In Firefox, the mouse scroll won't turn on (in other browsers, this code works well). Please can anyone help locate the error?
$("#enable_scroll").on("click", function () {
if ("onmousewheel" in document) { // for brouzers except FF
document.onmousewheel = function(e){};
} else { // for FF
document.addEventListener('DOMMouseScroll', function(e){});
}
});
This works everywhere: https://github.com/brandonaaron/jquery-mousewheel/blob/master/jquery.mousewheel.js
You use it like this:
$('#test3')
.hover(function() { log('#test3: mouseover'); }, function() { log('#test3: mouseout'); })
.mousewheel(function(event, delta, deltaX, deltaY) {
log('#test3: I should not have been logged');
})
.unmousewheel();

The simplest solution to hide calendar on blur or click

http://jsfiddle.net/SXrAb/
Following the jsfiddle link there is a simplified sample of what I need. Currently it shows the calendar on button click, and hides it on input blur.
What I cannot implement additionally is hiding calendar on button click.
So - calendar should:
open on button click if hidden (done)
hide on blur (done)
hide on button click if opened (this is what I'm in stuck with, because blur is triggered before button click event so I have no chance to handle it properly)
UPD:
the solution is expected to work correctly in all cases, like "mousedown on button, drag below, mouseup" (otherwise I wouldn't ask it ;-)
Try this:
var $calendar = $('#calendar');
var mousedown = false;
$('#calendar-input').blur(function() {
if (!mousedown)
$calendar.hide();
});
$('#calendar-button').mousedown(function() {
mousedown = true;
});
$('#calendar-button').mouseup(function() {
mousedown = false;
});
$('#calendar-button').click(function() {
if ($calendar.is(':visible')) {
$calendar.hide();
}
else {
$calendar.show();
$('#calendar-input').focus();
}
});
Demo here: http://jsfiddle.net/Tz73k/
UPDATE: OK, I moved the mouseup event to the document level. I don't think the mouse state can be tricked now by dragging the mouse before releasing it:
var $calendar = $('#calendar');
var mousedown = false;
$('#calendar-input').blur(function() {
if (!mousedown)
$calendar.hide();
});
$('#calendar-button').mousedown(function() {
mousedown = true;
});
$(document).mouseup(function() {
mousedown = false;
});
$('#calendar-button').click(function() {
if ($calendar.is(':visible')) {
$calendar.hide();
}
else {
$calendar.show();
$('#calendar-input').focus();
}
});
Updated fiddle: http://jsfiddle.net/yQ5CT/
It's helpful to think of the calendar and the button as a set, where you only hide the calendar when everything in the set has blurred. To do this you need a system where focus can be "handed off" between the calendar and button without triggering your hide function. To do this you'll need a focus and blur handler on both your calendar and your button, as well as a state variable for isFocused.
var isFocused;
jQuery('#calendar,#calendar-button,#calendar-input').blur(function(){
isFocused = false;
setTimeout(function() {
if (!isFocused) { hide(); }
}, 0);
});
jQuery('#calendar,#calendar-button,#calendar-input').focus(function(){
isFocused = true;
});
The setTimeout is because, when you click the button, focus is lost on calendar before it's gained on the button, so there's momentarily nothing in focus.
Edit
I guess there's actually three elements in the set, the button, the textbox, and the calendar. I updated the example. This also fixes the issue that, in your example, you can't click between the calendar and the textbox without the calendar hiding. Presumably the real calendar can be manipulated by clicking it.
Edit 2
For this to work you'll need to make your calendar focusable by giving it a tabindex.
<span id="calendar" tabindex="-1">I'm a calendar ;-)</span>
Hiya Demo here http://jsfiddle.net/SXrAb/50/ -- (non alert version) http://jsfiddle.net/SXrAb/51/
Thanks zerkms!
JQuery Code
var $calendar = $('#calendar');
$calendar.hide();
var isBlurEventInvoked = true;
var calendarShow = false;
$('#calendar-input').blur(function() {
alert(isBlurEventInvoked + " ==== " + calendarShow);
if (isBlurEventInvoked && calendarShow){
$calendar.hide();
isBlurEventInvoked = true;
}
});
$('#calendar-button').click(function() {
if (!$calendar.is(':visible') && isBlurEventInvoked){
$calendar.show();
$('#calendar-input').focus();
calendarShow = true;
isBlurEventInvoked = true;
}else if ($calendar.is(':visible')) {
$calendar.hide();
isBlurEventInvoked = false;
calendarShow = false;
}
});
​

Categories

Resources