disable scrolling on input focus in javascript - javascript

I was wondering if it was possible to stop the page from scrolling using javascript when a user type or clicks on a <input type="text"></input>

So I figured out how to accomplish this, and I will leave this as a record for anyone else who needs to solve this problem. (NOTE : this solution has only been tested on safari and Firefox)
for:
<input id="text" type="text" />
the function
document.getElementById('text').onkeydown = new function(event){return false}
Will not cause the window to shift the scroll so that a user can see the input field when he types into the field. If like me you want this to happen for some letters but not for others simply edit the contents of the onkeydown function so that it returns false for certain keycodes and true for others.

I faced up with similar problem. Try to use following solution: subscribe on focus event, disable window scroll in it's handler and turn scroll on by timeout.
I know solution seems not very clean, but demo looks nice, without visual defects.
$(function() {
var oldScroll = window.onscroll;
$(document).on('focus', 'input', function(e) {
window.onscroll = function () {
window.scroll(0,0);
} ;
setTimeout(function() {
window.onscroll = oldScroll;
}, 100);
});
});
http://jsfiddle.net/N4da4/8/

You could possibly set the scrollTop property to x every n milliseconds. The problem with that approach I would think would be that the page would look jerky (technical term) when the user attempted to scroll the page.
Besides, you'd be breaking the expectations of the user that they be able to scroll the page at any time which I would recommend against as it could confuse them at best and annoy them at worst.

Related

Shortcut keys for Javascript game GUI

I've been making a simple javascript based OOP text game that uses string replacement and variable adjustments tied to button .onclick events. I've been asked to add hotkeys for easier access, and I've been struggling with how to do it.
First I tried using the JSQuery hotkeys script and the .bind command, but that seemed like it would be very time consuming as I'd have to recode every .onclick as a hotkey, and even with unbind, it was firing off every event tied to the key on the script.
I feel like the best way to do would be if I could code the keys to the gui, i.e. if when you pressed "1", it activated the .onclick of button 1, that way the hotkey would be static (except when the button is disabled), but I've no idea how to do that. I've just been using html buttons, (i.e. input type="button" value="" disabled="disabled" id="button1"), I suspect I'd need something more sophisticated?
Thanks in advance for any help, google has been useless.
[EDIT - General description of code]
The way the game works is very simple, via the calling of functions as new events with different text/buttons (and different onclick events tied to those buttons). As an example, the start screen code is:
function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});
$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();
loadData();
});
$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();
});
});
}
Since the code executed by button one changes between functions, what the hotkey does as well, which was my problem with using the JQuery library code.
When a key is pressed then the event onkeypress is fired. This event provides some values like:
keyCode
charCode
which
So you could do something like:
window.onkeypress = function (event) {
// the keyCode value for the key 1 is 49, for the key 2 is 50
if (event.keyCode == 49) {
// execute the same code as clicking the button 1
console.log("The key 1 was pressed.");
} else if (event.keyCode == 50) {
// execute the same code as clicking the button 2
console.log("The key 2 was pressed.");
}
};
Now, when a user visits your website he could press the keys 1 or 2 on the keyboard and fire the same logic as clicking the buttons "1" and "2" (being something like <input id="button1">) with the left mouse taste.
If you have really a lot of hotkeys then this would be also tedious to type, but without knowing your code I can hardly give you a complete solution. I hope my answer can give you some idea how to proceed further.
EDIT:
Further reading on the topic:
http://unixpapa.com/js/key.html

'taphold' event disabled after focus on a textbox

I have been using the jQuery UI mobile library and have the following method bound to an element for 'taphold':
// Apply class to annotations details to initiate animation
$('.detailsDiv').on('taphold', function ()
{
var openingID = $(this).parent().attr("annoID");
var showControls = true;
if ($(".annoEditableTextArea.annoName").length > 0)
$('body').append(pThis._getBlackoutOverlay(id));
}
else
{
$(this).off('mousedown');
pThis.base.annotations._setAnnotationDetailsActive(openingID, showControls);
}
});
This hooks the event just fine. However, on iOS safari if I click on a textbox from here after the 'taphold' event does not fire. I've tried to reattach the event after an unfocus of a textbox but still no luck.
Has anyone had any similar experiences with this sort of behavior?
Many thanks
I could not pin point the exact reason behind this, however I found a similar library from some guys called zauberlabs:
https://github.com/zauberlabs/jquery-tap-and-hold
This was a straight swap, with no extra coding required and solved the problem.
Many thanks,

How can I put a button in the down state?

Suppose I have a button, which goes into a down state when someone clicks on it, but before the mouse is released.
Now suppose instead that someone presses the 'a' key, I want the button to go into the down state, until the key is released, at which point it is triggered. Is this possible?
After dooing some research here is the final answer I got:
You can trigger mousedown or mouseup events on a button element using keyup and keydown
if your button is programmed to change its style according to these events than you are good to go.
See this fiddle example: http://jsfiddle.net/FwKEQ/15/
Note that if you use jQuery's UI components than it does work. But for standard buttons there is no way that you can move them to their pressed state using javascript
html:
<button id="jQbutton">Press 'A' to move me to pressed state</button>
Javascript:
<script>
$( "#jQbutton" ).button();
$(document).keydown(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mousedown();
});
$(document).keyup(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mouseup();
});
</script>
EDIT:
There might be a hack that we could utilize:
using accesskey for the button element and then try to simulate the accesskey press (that i am not sure if possible)
here is where i'm at so far http://jsfiddle.net/FwKEQ/28/
EDIT 2:
So looking further into this topic i have found the following:
Default buttons (without styles) are rendered by the OS, I was not able to find a formal proof for that but if you try to load the same page using a mac OS you'll get mac OS style buttons while in windows you will get the "ugly" gray button.
Because the default buttons are rendered by the OS they comply to OS events meaning events that are sent by the browser and are trusted.
this is not true for custom styled buttons as they comply to CSS an JS to change their appearance on press that is why the JQ button is affected by JS.
so to summarize you would need a trusted press event to fire on a default button to change its style and that cannot be done due to security constraints.
read a bit more about trusted events here: http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events
and if someone could find a formal reference with regards to the default buttons being rendered by the OS please comment or edit this answer.
Unfortunately the rendering of the active state on default buttons neither
is a simple matter of css styling nor can be easily changed by applying
javascript.
An option to do this on default buttons is to use the hotkeys jquery plugin: https://github.com/jeresig/jquery.hotkeys or implement alternative key codes for different browsers.
and to apply 50% opacity to the default button when pressed (to indicate the keydown).
(To me it seems almost perfect ;-) It probably is as good as it can easily get to work across platforms and browsers using default buttons.
jsfiddle DEMO
and the code ...
html:
<button id="test">Test Button</button>
Selected: <span class="selected" id="out"></span>
javascript:
$('#test').click(function () {
fn_up();
});
fn_down = function(event){
$('#test').css("opacity", 0.5);
$('#test').focus();
event.preventDefault();
}
fn_up = function(event){
$('#test').css("opacity", 1);
$('#out').append(" test");
event.preventDefault();
}
//to bind the event to the 'a' key
$(document).bind('keydown','a', fn_down);
$(document).bind('keyup','a', fn_up);
//to get the same effect with the 'space' key
$(document).bind('keydown','space', fn);
$(document).bind('keyup','space', fn2);
In the fiddle I apply it to the space button and the mousedown/up to achieve the same effect with all events (but you could just use it with the 'a' key ... this is a matter of taste).
Here is a jsfiddel that shows how it's done using jQuery: http://jsfiddle.net/KHhvm/2/
The important part:
$("#textInput").keydown(function(event) {
var charCodeFor_a = 65;
if ( event.which == charCodeFor_a ) {
// "click" on the button
$('#button').mousedown();
// make the button look "clicked"
$('#button').addClass('fakeButtonDown');
// do some stuff here...
// release the button later using $('#button').mousedown();
}
});
The button event is triggered when entering "a" in the input field. But as Mark pointed out you need to fake the styling for the clicked button because the browser doesn't do it.
Edit: I'm not sure if you're using jQuery in your project. I just wanted to show that it is possible at all. If it can be done with the jQuery library there is also a way to do it in pure javascript. ;)

How to simulate as if user pressed Ctrl "plus" plus or minus using javascript (JQuery)?

Is this possible if I click on an anchor link to simulate as if I have pressed Ctrl+ keys on the keyboard (or equivalent on Mac)? if yes, could you show me how to do this, please?
something like
Ctrl+
If you just want to simulate the behaviour of the CTRL+Mousewheel Zoom function, you can use CSS3-Transitions. A nice jQuery plugin for this is jquery Transit.
Example:
$('a.ctrlplus').click(function() {
$('body').transition({ scale: ($('body').css('scale')+0.1) });
});
Don't know if it works in all Browsers.
I'm pretty sure you will need to access this on the browser API level, since not all browsers have this functionality or do it the same way.
I cannot understand what you are going to achieve, but here is a plugin, which made handling keyboard shortcuts very easier.
Here is an example
shortcut.add("Ctrl+Shift+X",function() {
alert("You have pressed Ctrl+____");
});
Hope it will help you.
To simulate the zoom function, you can use CSS property "zoom".
For JS, it's like:
function simulateCtrlKeyPlus() {
let currentZoom = parseFloat(document.body.style.zoom) || 1
document.body.style.zoom = currentZoom * 1.1
}

Programmatically set focus of input box from ListView's ItemInvoked event [Windows 8 Metro HTML5]

Edit: If you have not developed on Windows 8, do not try to answer this question. Do not vote on it. Do not even read it. This is not a web app or website and does not run in a browser. Please stop down-voting content you do not understand. This is a Windows 8 METRO HTML5/js application that runs in the Windows Runtime environment.
Original Question:
I want the cursor to be "blinking" in the input box, ready to receive input. I'm using javascript to set the focus. This isn't working:
document.querySelector("#input-box").focus();
Anyone know why? Is the focus method not the correct one to use for this?
Thank you.
Edit #2: So it definitely has something to do with the fact that I am trying to set focus to the input from a ListView's "itemInvoked" event. The event is firing properly, the element is accessible from the event handler, and the line has no errors on execution. I can set focus to my input tag from a standard button click event, but not from an ItemInvoked event. So the question is, why can't I set focus from within this event handler?
I have created this little test project with only a textbox and in the onload set the focus in exactly the same way as you do. I tried it both on the emulator and on my local machine and both methods seem to work.
Could you try if this project is working for you on your machine? And can you give us some more insight on when you are trying to set the focus? Right now in your question there is not that much information about when it's happening.
You can download the sample over here http://www.playingwith.net/Temp/TestFocusApplication.zip
Update
Okay, seem to found it, if you call the msSetImmediate function with the function that sets focus to the textbox it seems to work. I don't have an option to upload the test example, so below you find the code where I attach the ItemInvoked handler and call the setFocus function.
var listView = document.getElementById("basicListView");
listView.winControl.addEventListener("iteminvoked", function (evt) {
if (listView.winControl.selection.count() > 0) {
msSetImmediate(setFocus);
}
});
function setFocus() {
//Set focus on input textbox;
var input = document.querySelector("#input-box")
input.focus();
}
Which build are you on ? consumer preview or other dev previews ? I'm on DP6 (available to MS partners) and the JS standard stuff works.
In my default.html I have:
<input id="input1" type="text" value="one"/>
<input id="input2" type="text" value="two"/>
<input id="focus_btn" type="button" value="Set focus 1"/>
<input id="focus_btn2" type="button" value="Set focus 2"/>
And then in my default.js, in the app-launched-loaded boilerplate function I have:
document.querySelector('#focus_btn').addEventListener('click', function () {
var input1 = document.querySelector('#input1').focus();
});
document.querySelector('#focus_btn2').addEventListener('click', function () {
var input1 = document.querySelector('#input2').focus();
});
The only reason I can think of it not working is that the element is accessed before it is ready. That or earlier build bugs. I have the solution rar'd in : http://www.mediafire.com/?ghz49gtfxlgr7en if you want to see.
Try using non-jquery regular javascript like
document.getElementById( 'myElementsID' ).focus()
Try this to see if it helps:
if(document.createEvent)
{
document.getElementById('input-box').dispatchEvent('DOMFocusIn');
}
else
{
document.getElementById('input-box').fireEvent('DOMFocusIn', event);
}
Although the question is very old. But I struggled to find the solution for this.
First thing .focus() does not return any value it just set focus and undefined is returned.
Also, when we set focus on some element make sure that element has the tabindex present, otherwise it would not focus (mainly in chrome).
The following query may be used:
element.querySelector('#label').setAttribute('tabindex','0');
element.querySelector('#label').focus();

Categories

Resources