Capture click and keystroke events in Javascript, override default behavior? - javascript

I've written some JavaScript code using jQuery that listens for the user to click the mouse on different parts of my page with and without holding down the shift key.
I have a table on my page. The idea is that the user can select rows in the table by clicking on them. The user can select multiple rows by clicking one row, holding down shift, and clicking another row. (This is how the user expects to select multiple rows, but holding down the shift key, right?)
Anyways, my code works in Internet Explorer, but I have a problem. My code reads the users selection, but the browser simultaneously highlights the text between the two mouse click locations.
How can I make it so that my code can select the rows based on the user clicks and the browser doesn't select the text?
Update I tried the following code:
$('tr').bind('mousedown',function() { return false; } );
With this code in my page, when I click one row, hold down shift and click another row, the text between the two rows is highlighted. This is what I'm trying to suppress. Please note that the text highlights before I release the mouse button.
Update #2 I tried the following code:
$('tr').bind('mousedown',function(e) {
e.preventDefault();
return false;
});
Unfortunately, this doesn't seem to do anything at all.

It's the mousedown event you want to suppress.
Have a look at event.stopPropogation() and event.preventDefault().

The return value of an event handler is ignored by specification (jQuery might to additional stuff).
You may be looking for preventDefault and returnValue (this latter one was invented precisely because the return value of a handler is ignored).
You may also want to look into the CSS3 property extension -moz-user-select: none.

Try this
$(function(){
$("tableSelector").bind('selectstart mousedown',function () {
return false;
});
});

Related

jQuery: generate Select element

I have a table with data, and when I click on a cell in a certain column, I want it to change into a select dropdown for the user to choose a category for that row (which will be written to the database by AJAX but that'll come later).
I've done something similar before with text boxes using this, which works great, but I'm not sure if I'm modifying it correctly.
I've created a JSFiddle which shows the problem I'm having. I click on the text and it turns into a select element as expected, but when I click on that to choose an option, the dropdown doesn't stay open and I can't select anything. Debugging has shown me that when I click the dropdown, it runs the $("td.ChooseType").click() routine again so I've tried to suppress that by removing the class then adding it back on on selection, but that hasn't solved it. On the rare occasion that the dropdown stays open, I am unable to select anything by either mouse or keyboard.
All of the users will be on IE8 unfortunately, so I need it to be compatible with that.
Thanks!
You need to use event delegation, as otherwise that click event is always bound to that td - regardless of whether its class changes.
Simply change:
$("td.ChooseType").click(function() {
To:
$("table").on('click', '.ChooseType', function () {
JSFiddle demo.
Purely as an alternative to the accepted answer, you can remove an attached handler with unbind. So instead of adding and removing the class, you could unbind and rebind your handler. Only requirement is that the function can't be in-line, but has to be declared separately.
example: http://jsbin.com/qiqunici/1/edit
var handler = function () {
$(this).unbind('click', handler); //unbind the clicked element only
//create and change the element
//inside the select-change event, instead of addClass, re-attach:
{
//$(this).parent().addClass("ChooseType").text(selected).find('select').remove();
$(this).parent().click(handler).text(selected).find('select').remove();
}
};
$("td.ChooseType").click(handler);

How to prevent deselection of selected text on blur (focus lost) in html

I have been doing research on this simple sounding issue for a couple of days and I have not seen any result.
In a nutshell my problem is as follows: I would like to select text in a some input field, move focus to another field (or generally speaking some other element), but not lose my selected text.
Such a situation could correspond to a use-case in which I select text in a field, right-click and display a custom popup menu, but do not wish to lose focus of selected text, because I want to do some operations on the previously selected text.
A small code test sample would be (for my initial simple scenario - here I am forcing text selection when the second input field gains focus):
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="text1" size="20" value="Test1"/>
<input type="text" id="text2" size="20" value="Test2"/>
<script>
$('#text2').focus( function (evt) {
var target = $('#text1')[0];
target.select();
console.log('active/focused element: ' + document.activeElement.id);
});
</script>
</body>
</html>
I have been searching SO and web for a solution to this and have not seen much if any help.
I am not sure this is even really possible (due to the link between blur and selection lost and focus and selection). I have seen a style property called preventDeselect, in another SO answer - this does not work and I have not even such documentation or browser support for this.
I am quite struggling with this and would appreciate some help: even saying I can't do this at all or maybe some ways to go.
UPDATE:
Just for the record, my user scenario, which refers to text selection and context menu, is a common one (it slipped my mind to mention): just select some text in this page (or in an input type field) and right click to get the browser's default context menu - my scenario is different in that i want to use a custom menu, but with similar behavior to the browser's context menu - which normally allows to select some text, cut/copy the selection, navigate within the context menu without losing the selected text. So I think it should be possible somehow :) to do all these things with a context menu and still have your selection.
Attempting to answer this part of your question:
Such a situation could correspond to a use-case in which I select text
in a field, right-click and display a custom popup menu, but do not
wish to lose focus of selected text, because I want to do some
operations on the previously selected text.
For this use-case, I created a quick fiddle: http://jsfiddle.net/4XE9a/1/
Note: Am using the same getSelection function from #David's answer.
If you select any text and then right-click on the input, a custom popup menu appears. Click "option 1". You will find that the selection is not lost even though the focus has shifted to that anchor tag.
However, for the second part of your question regarding focus shifting to another textbox, #David's answer suffices.
Update: (after your comments)
Please see this updated fiddle: http://jsfiddle.net/783mA/1/
Now, when you select some text and right-click on the input it will show the custom popup menu with three options. Use tab to navigate and press space or click on the highlighted option. (Due to paucity of time I could not implement up/down arrow keys, but the concept remains the same)
This demonstrates your question in the comment that the selection is still not lost while navigating the menu.
Note: You are wanting to visually keep the selection highlight and not lose the selection while clicking anywhere else. Please note that this is not possible because text selection behavior is OS implemented. Browser, html etc do not play a role here. The text selection is lost as soon as you click anywhere outside the context of selection. This is because the system starts expecting a new selection as soon as you click anywhere outside. However, controls without text surface are exempt. Button, scrollbar arrows etc will not cause selection to lose.
To view this behaviour, in the fiddle, select some text and then click any dropdown on the left pane. The text selection is not lost, even visually for that matter.
This is why in the new fiddle above, I purposely used buttons to demonstrate.
You can save each selection in an interval, then retrieve it when you like. Here is an example that pulls the selection when the input has focus and clears the interval on blur:
function getSelection(elm) {
var start = elm.selectionStart;
var end = elm.selectionEnd;
return elm.value.substring(start, end);
}
$('input').focus(function() {
var self = this;
$(this).data('interval', setInterval(function() {
$(self).data('selection', getSelection(self));
},20));
}).blur(function() {
clearInterval($(this).data('interval'));
});
Now you can stuff like:
$('#text2').focus(function() {
console.log('selection in #text1 was: '+$('#text1').data('selection'));
});
Demo: http://jsfiddle.net/qCCY5/

Setting focus on next dropdown instead of using blur() method?

Problem:
I have many drop downs with dynamic changes going on at all times. The problem is I am having to use the blur() method to disable focus so that the class depending on the selected value can be applied.
Is there a way I can set the focus onto the next drop down element.
Tried:
Instead of blur(), I have tried this but it did not work.
this.next(".Element").focus();
Current code:
$('.Element').change(function () {
var colour = $(this).find('option:selected').attr('class');
$(this).removeClass().addClass(colour);
this.blur();
}).change
JS Fiddle:
jsfiddle of my code
try to make this a jQuery object to focus another element
$(this).next(".keyTechElement").focus();
EDIT 1:
Seeing your DOM, changes is needed. The .next() function selects siblings in the DOM and inside <td> there is no .Element sibling.
$(this).blur();
$(this).closest('td').next("td").find(".Element").focus();
http://jsfiddle.net/UXJZ7/2/
I think manipulating focus with focus() or blur() is terrible for keyboard users.
Users also detest auto-tabbing on forms they rarely use.
Onchange doesn't mean a selection has been made, a user could be stepping through the options with the keyboard (or with assistive technology that simulates the keyboard like speech recognition software), you get an onchange event for every step in their selection.
You can get quite elaborate to work around this, but it's rarely worth the effort.
For your example, I'd just leave things like this: http://jsfiddle.net/KWvMZ/ It looks like the only reason you have a focus state in your style is to display the text with sufficient contrast, so I just set the yellow background to have black text when focussed and left it like that.
.

Acrobat 10: Run Javascript whenever a different item is highlighted in a dropdown

I would like to know if its possible if I can have javascript change the values of other fields based on a user highlighting different options in a dropdown box before actually selecting the option?
So let's the user uses the mouse or arrows key to navigate through the list, before selecting an item. I would like other texts boxes to change their values as a result of this scrolling.
For the record, I have searched quite a bit. Also, the event actions (i.e. - mouse up, mouse down) only work when the dropdown box is first entered. Not on subsequent actions ... at least as far as I can tell. I also have commit selected value immediately checked, which helps because you don't have to leave the box before it fires.
Is what I want possible? Or can the scripts only run after the selection is committed?
Dropdown properties>Calculate>Custom calculation script. Place the script in that box for it to instantly update another place.
Use this formula in script:
var one = this.getField("fieldName 1").value; //fieldname 1 should be name of dropdown field//
if(one=="Administration") getField("fieldName 2").value = "Chief";<br>
if(one=="Apparatus Maintenance") getField("fieldName 2").value = "Engineer";<br>
if(one=="Confined Space") getField("fieldName 2").value = "Rescue Technician";
I think you should be able to fire some JavaScript whenever user changes highlighted option using keyboard. Because whenever a key is pressed, the OnKeyPress event of the combo is fired.
Support for mouse is trickier. When user hovers mouse pointer over an item in combo, no event is fired. The same OnKeyPress event is fired only when user actually clicks on an option.

Switchable selectable text

I have a table which is filled with data from a database. Some javascript allows a user to select certain rows and take some actions. I allow users to click one row and then to shift click another row to create a group (as well as alt-click to select/deselect individual rows).
The problem is I don't like how the text highlights when they shift click. Is there some CSS setting or javascript/jQuery solution to disable the selectable text (cross browser preferablly or just in firefox).
If possible I also want to be able to let the user select text to copy and paste sometimes or inside a textbox form input inside the same table so I would like to be able to enable and disable the selecting of text somehow. Any ideas?
this should do the trick:
$('td').disableSelection();
example:
http://jsfiddle.net/GhfuJ/1/
Here's one way you could completely disable text selection:
$("selector").bind($.support.selectstart ? "selectstart" : "mousedown", function(event) {
event.preventDefault();
});
This is how jQueryUI implements its disableSelection() method.
You could tailor your selector to exclude textarea elements, or wrap code inside the event handler with an if block that evaluates a boolean that gets set under certain circumstances (For example, you could turn on booleans when the user is clicking or shift/alt + clicking).

Categories

Resources