Disable text selection dynamically per click via javascript? - javascript

I have a table which I've added some multiple selection functionality where shift + click selects rows between the first click and second click but it ends up highlighting all text between the rows.
I don't want to disable text selection via CSS because this stuff really does need to be selectable, just not when shift + clicking when my multi-select function fires.
Can this be done?
var lastChecked;
$("#contact_table tr").click(function(e) {
if (e.target.getAttribute('type') == 'checkbox') {
return;
};
if (e.shiftKey && lastChecked) {
// select between last point and new point
var tableRows = $("#contact_table tr");
var newRow = tableRows.index($(this));
var oldRow = tableRows.index(lastChecked);
if (oldRow < newRow) {
newRow = newRow +1;
}
var sliceRange = [newRow, oldRow].sort();
var selectedRows = tableRows.slice(sliceRange[0], sliceRange[1])
.find('input[type=checkbox]').attr('checked', true);
} else {
var checkbox = $(this).find('input[type=checkbox]');
var checked = toggleCheckbox(checkbox);
if (checked) {
lastChecked = $(this);
}
};
recalculateSelectedButton();
});

You can deselect all text with javascript; add a call to RemoveSelection() after you run the multi-select logic.
From http://help.dottoro.com/ljigixkc.php via Clear a selection in Firefox
function RemoveSelection () {
if (window.getSelection) { // all browsers, except IE before version 9
var selection = window.getSelection ();
selection.removeAllRanges ();
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
document.selection.empty ();
}
}
}

You can try disabling user select based on the number of checked checkboxes. If there are any, just add the CSS style user-select: none; (and prefixed versions) to the #contact_table.
If you provide a jsfiddle with your current javascript code and table, I'd test the code too - now it's as-is ;) I'm not sure how the click interactions will play out with any cancelled event bubbling etcetera. Also, this implementation doesn't take into account that users might want to select text even if there's a checked checkbox (so it might not be what you're looking for).
$(function() {
var $contactTable = $("#contact_table"),
userSelectNoneClass = "user-select-none";
$contactTable.on("change", ":checkbox", function(e) {
var numberOfCheckedRows = $("#contact_table :checkbox:checked").length,
anyCheckedRows = (numberOfCheckedRows > 0);
if (anyCheckedRows && $contactTable.hasClass(userSelectNoneClass)) {
$contactTable.addClass(userSelectNoneClass);
} else {
$contactTable.removeClass(userSelectNoneClass);
}
});
});
.user-select-none
{
/* From https://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Edit: using the change event instead.

Related

Dragging on html table cells

Fiddle
$(document).live('mouseup', function () {
flag = false;
});
var colIndex;
var lastRow;
$(document).on('mousedown', '.csstablelisttd', function (e) {
//This line gets the index of the first clicked row.
lastRow = $(this).closest("tr")[0].rowIndex;
var rowIndex = $(this).closest("tr").index();
colIndex = $(e.target).closest('td').index();
$(".csstdhighlight").removeClass("csstdhighlight");
if (colIndex == 0 || colIndex == 1) //)0 FOR FULL TIME CELL AND 1 FOR TIME SLOT CELL.
return;
if ($('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).hasClass('csstdred') == false) {
$('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).addClass('csstdhighlight');
flag = true;
return false;
}
});
i am Dragging on table cells.
While dragging(move downward direction) i have to move table scroll also.
and also i want to select cells reverse (upward direction).
what should i do.
I have make an selection on tr class.
Updated jsFiddle: http://jsfiddle.net/qvxBb/2/
Disable normal selection like this:
.myselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
}
And handle the row-selection with javascript like this:
// wether or not we are selecting
var selecting = false;
// the element we want to make selectable
var selectable = '.myselect tr:not(:nth-child(1)) td:nth-child(3)';
$(selectable).mousedown(function () {
selecting = true;
}).mouseenter(function () {
if (selecting) {
$(this).addClass('csstdhighlight');
fillGaps();
}
});
$(window).mouseup(function () {
selecting = false;
}).click(function () {
$(selectable).removeClass('csstdhighlight');
});
// If you select too fast, js doesn't fire mousenter on all cells.
// So we fill the missing ones by hand
function fillGaps() {
min = $('td.csstdhighlight:first').parent().index();
max = $('td.csstdhighlight:last').parent().index();
$('.myselect tr:lt('+max+'):gt('+min+') td:nth-child(3)').addClass('csstdhighlight');
}
I just added a class in the HTML. All the HTML and CSS in unchanged besides what I've shown here.
Updated jsFiddle: http://jsfiddle.net/qvxBb/2/
There are several problems with your table, but I will correct the one you asked for.
To make your table scroll when your mouse get outside the container, add this code inside your mousedown event handler :
$('body').on('mousemove', function(e){
div = $('#divScroll');
if(e.pageY > div.height() && (e.pageY - div.height()) > div.scrollTop()) {
div.scrollTop(e.pageY - div.height());
}
});
and this, inside your mouseup event handler :
$('body').off('mousemove');
See the updated Fiddle
But now, another issue appear. This is because of the rest of your code. The lines are not selected because the mouse leave the column.
Try removing the return false; inside
$('#contentPlaceHolderMain_tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).addClass('csstdhighlight');
flag = true;
return false; //Remove this line
}
Because return false; stops browser default behavior (scrolling automatically).
DEMO

How to prevent the double-click select text in Javascript

Say I have an ul (li) list in the page:
<ul>
<li>xxx<li>
<li>xxx<li>
</ul>
The element li are clickable and double-clickable, they are attached with these events, and I return false in both of them.
$('ul li').on('click',function(){
//do what I want
return false;
}).on('dblclick',function(){
//do what I want
return false;
});
But when the user double-clicks the element, the text inside the li will be selected. How can this be prevented?
Update:
Solved now,I use the following code with the css selector by NiftyDude:
$('ul li').on('click',function(){
//do what I want
return false;
}).....on('dragstart',function(){return false;}).on('selectstart',function(){return false;});
You can disable text selection using css (Note that this will effectively disable all selection methods and not just double clicking)
ul li {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
http://jsfiddle.net/T3d7v/1/
You can't stop the select from happening 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>
To also prevent selecting whole paragraph by "triple click", here is the required code:
var _tripleClickTimer = 0;
document.ondblclick = function(evt) {
ClearSelection();
window.clearTimeout(_tripleClickTimer);
//handle triple click selecting whole paragraph
document.onclick = function() {
ClearSelection();
};
_tripleClickTimer = window.setTimeout(function() {
document.onclick = null;
}, 1000);
};
function ClearSelection() {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
Source/Live test.
This should work on any browser, please report any browser where it's not working.

jqTransform Select - Scroll to letter typed

I've got a form that uses jqTransform to replace the standard select boxes and radio buttons. It all works fine and dandy, except one thing that annoys me:
Since it replaces the select box with a list of links, when you type a letter to scroll it doesn't do anything. For instance, you click to open up the select, then type an S. It should scroll to the first S in the list, but nothing happens. Is there a way to re-instate this functionality? Below is the jqTransform code for the select box. I don't see a handler for this type of thing:
/***************************
Select
***************************/
$.fn.jqTransSelect = function(){
return this.each(function(index){
var $select = $(this);
if($select.hasClass('jqTransformHidden')) {return;}
if($select.attr('multiple')) {return;}
var oLabel = jqTransformGetLabel($select);
/* First thing we do is Wrap it */
var $wrapper = $select
.addClass('jqTransformHidden')
.wrap('<div class="jqTransformSelectWrapper"></div>')
.parent()
.css({zIndex: 10-index})
;
/* Now add the html for the select */
$wrapper.prepend('<div><span></span></div><ul></ul>');
var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
/* Now we add the options */
$('option', this).each(function(i){
var oLi = $('<li>'+ $(this).html() +'</li>');
$ul.append(oLi);
});
/* Add click handler to the a */
$ul.find('a').click(function(){
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
/* Fire the onchange event */
if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
$select[0].selectedIndex = $(this).attr('index');
$('span:eq(0)', $wrapper).html($(this).html());
$ul.hide();
return false;
});
/* Set the default */
$('a:eq('+ this.selectedIndex +')', $ul).click();
$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
this.oLabel = oLabel;
/* Apply the click handler to the Open */
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.click(function(){
//Check if box is already open to still allow toggle, but close all other selects
if( $ul.css('display') == 'none' ) {jqTransformHideSelect();}
if($select.attr('disabled')){return false;}
$ul.slideToggle('fast', function(){
var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
$ul.animate({scrollTop: offSet});
});
return false;
})
;
// Set the new width
var iSelectWidth = $select.outerWidth();
var oSpan = $('span:first',$wrapper);
var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
$wrapper.css('width',newWidth);
$ul.css('width',newWidth-2);
oSpan.css({width:iSelectWidth});
$ul.css({height:'420px','overflow':'hidden'});
// Calculate the height if necessary, less elements that the default height
//show the ul to calculate the block, if ul is not displayed li height value is 0
$ul.css({display:'block',visibility:'hidden'});
var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
$ul.css({display:'none',visibility:'visible'});
});
};
Here is what we tried to do to implement this:
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.keypress(function (e) {
$.each(myArray, function (i, l) {
var sc = l.substr(0, 1).toLowerCase();
var kc = String.fromCharCode(e.which);
if (sc == kc) {
$select[0].selectedIndex = i;
$('span:eq(0)', $wrapper).html(l);
$ul.hide();
return false;
}
});
});
Oh dang. I was missing the big picture without the code. Now I see what's going on... yeah, there's no "reinstating" the functionality since the new list of links is not actually a select box anymore. If jqTransform doesn't include a scrollable option by default I think you'll have to implement one.
If you look at their demo page, their "plain" select box works as expected (although it's hard to notice since all options start with "O", it WILL jump to the first "Option") and their styled select box does not.
Without looking deeper at the code, I suspect that means that a keypress capture is not implemented in the plug-in itself.
I'm afraid this isn't the "answer" you were probably hoping for. With any luck someone who has done this sort of thing before will hear your plea. ;-)
solution for jqTransform select keypress work link visit http://www.techapparatus.com/jqtransform-select-problem-with-keyboard-type-solution
Add the following code at the end of return this.each(function(index){ ... }); that is inside of $.fn.jqTransSelect function.
Also you have to install the scrollTo jquery plugin.
CODE:
var newChar;
$(document).bind("keydown", function (e) {
var char = String.fromCharCode(e.which);
var code = e.keyCode || e.which;
var charFound;
if( $ul.css('display') != 'none' ){
if (newChar != char){
newChar = char;
$ul.find('a').each(function(){
// Find first occurence of li that starts with letter typed
if ($(this).text().substr(0,1).toUpperCase() == char && $(this).text() != "Choose"){
charFound = true;
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
$select[0].selectedIndex = $(this).attr('index');
$($select[0]).trigger('change');
$that = $(this);
return false;
}
});
if (charFound == true){
// Scroll to selected value
$ul.scrollTo($('a.selected', $ul), 400);
}
}
//If Enter has been pressed, select the value
if(code == 13) {
$('span:eq(0)', $wrapper).html($that.html());
$ul.hide();
return false;
}
}
});

How to have a popup after selecting text?

I can't seem to figure this out. I have a div with some text in it. When the user selects pieces of it (totally at random, whatever they want), I want a small popup to occur with the text inside of it.
To initiative the popup, can I just do this? ...
$('#textdiv').click(function() {
But then how do I get only the selected/highlighted text?
jQuery isn't going to be of much use here, so you'll need pure JS to do the selection grabbing part (credit goes to this page):
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
You were on the right track with the mouseup handler, so here's what I got working:
$('#test').mouseup(function() {
var selection = getSelected();
if (selection) {
alert(selection);
}
});
And a live demo: http://jsfiddle.net/PQbb7/7/.
Just updated first answer.
Try this
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
/* create sniffer */
$(document).ready(function() {
$('#my-textarea').mouseup(function(event) {
var selection = getSelected();
selection = $.trim(selection);
if(selection != ''){
$("span.popup-tag").css("display","block");
$("span.popup-tag").css("top",event.clientY);
$("span.popup-tag").css("left",event.clientX);
$("span.popup-tag").text(selection);
}else{
$("span.popup-tag").css("display","none");
}
});
});
.popup-tag{
position:absolute;
display:none;
background-color:#785448d4;
color:white;
padding:10px;
font-size:20px;
font-weight:bold;
text-decoration:underline;
cursor:pointer;
-webkit-filter: drop-shadow(0 1px 10px rgba(113,158,206,0.8));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select any text :<br>
<textarea type="text" id="my-textarea" style="width:100%; height:200px;" >
While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on 27 July 2015, aged 83. Thousands including national-level dignitaries attended the funeral ceremony held in his hometown of Rameshwaram, where he was buried with full state honours.
</textarea>
<span class="popup-tag"></span>
see: https://jsfiddle.net/arunmaharana123/kxj9pm40/
We've just released an jQuery plugin called highlighter.js that should allow you to do this flexibly. The code is https://github.com/huffpostlabs/highlighter.js, feel free to ask any questions on the github page.
You can get it from the base DOM element likeso:
var start = $('#textdiv')[0].selectionStart;
var end = $('#textdiv')[0].selectionEnd;
var highlight = $('#textdiv').val().substring(start, end);
// Note the [0] part because we want the actual DOM element, not the jQuery object
At this point, you just need to bind it to a click event. I think in this case mouseup is the event you'd want to bind to, since a user clicks and holds the mouse and then releases it after they're done highlighting text.
The problem is this would not trigger users that use only the keyboard to highlight text. For that you'd want to use keyup on the element and filter for the right keystrokes.
You need a event listener that listen to mouseup event.
var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);
// Lets listen to mouseup DOM events.
document.addEventListener('mouseup', function (e) {
var selection = window.getSelection().toString();
if (selection.length > 0) {
renderBubble(selection);
}
}, false);
// Close the bubble when we click on the screen.
document.addEventListener('mousedown', function (e) {
bubbleDOM.style.visibility = 'hidden';
}, false);
// Move that bubble to the appropriate location.
function renderBubble(selection) {
bubbleDOM.innerHTML = selection;
bubbleDOM.style.visibility = 'visible';
}

Checkbox click script - [SHIFT] check/uncheck range, [CTRL] check/uncheck all -- based on select name?

Would anyone know of a ready-made script or plugin providing:
-Shift click for check/uncheck all in range
-CTRL click to select or unselect all
That can works off the check inputs 'name' (instead of all on a page or all inside a div):
input[name='user_group[]']
input[name='record_group[]']
I've been using a couple of scripts (javascript and jQuery) but they're based on all checkboxes in a div or table and I'm not smart enough to roll my own or modify another script. Google searching on this has been a little difficult (too many common terms I think)...
Thanks Much Appreciated!
I started playing around with this script, although it's missing a CTRL+Click feature (select all/none control).
In it's original form it works against all checkboxes on a page. I changed the "$('input[type=checkbox]').shiftClick();" linke to "$("input[name='selected_employees[]']").shiftClick();" and as far as I can tell it seems to be working perfectly now against only the single checkbox group.
The only flaw (for my requirements) is there is not a CTRL+Click function to toggle check or un-check all checkboxes in the group.
<script type="text/javascript">
$(document).ready(function() {
// shiftclick: http://sneeu.com/projects/shiftclick/
// This will create a ShiftClick set of all the checkboxes on a page.
$(function() {
$("input[name='selected_employees[]']").shiftClick();
// $('input[type=checkbox]').shiftClick();
});
(function($) {
$.fn.shiftClick = function() {
var lastSelected;
var checkBoxes = $(this);
this.each(function() {
$(this).click(function(ev) {
if (ev.shiftKey) {
var last = checkBoxes.index(lastSelected);
var first = checkBoxes.index(this);
var start = Math.min(first, last);
var end = Math.max(first, last);
var chk = lastSelected.checked;
for (var i = start; i < end; i++) {
checkBoxes[i].checked = chk;
}
} else {
lastSelected = this;
}
})
});
};
})(jQuery);
});
</script>
I believe this should work!
Working demo on jsFiddle: http://jsfiddle.net/SXdVs/3/
var firstIndex = null;
$(":checkbox").click(function(e) {
$this = $(this);
if (e.ctrlKey) {
if ($this.is(":checked")) {
$("input[name='"+ $this.attr("name") +"']").attr("checked", "checked");
} else {
$("input[name='"+ $this.attr("name") +"']").removeAttr("checked");
}
} else if (e.shiftKey) {
$items = $("input[name='"+ $this.attr("name") +"']");
if (firstIndex == null) {
firstIndex = $items.index($this);
} else {
var currentIndex = $items.index($this);
var high = Math.max(firstIndex,currentIndex);
var low = Math.min(firstIndex,currentIndex);
if ($this.is(":checked")) {
$items.filter(":gt("+ low +"):lt("+ high +")").attr("checked", "checked");
} else {
$items.filter(":gt("+ low +"):lt("+ high +")").removeAttr("checked");
}
firstIndex = null;
}
}
});

Categories

Resources