Scroll div with arrow keys - javascript

This is similar to SO: how to move a div with arrow keys, so maybe a clear and informed 'no' suffices as an answer:
Can I make an overflowing div a "default scroll target" that reacts to arrow-up/down/page-down/space the same way as an overflowing document (i.e. scrolls down the content)? The page itself does not have a scrollbar (simple example below). In particular, can this be accomplished without explicitly tracking key events (neither directly nor hidded by a JS library)?
<html>
<body>
<div id="contentcontainer" style="height:200px;width:200px;overflow:scroll">
<div id="innercontent" style="height:2000px;">foo</div>
</div>
</body>
</html>
Edit: Of course the above works after I click into the div. Basically, I want to avoid having to do that...

In order for an html element to be focusable, it must be reachable with the Tab key. This means you can call .focus() on a link or an input. Additionally, body elements are always focusable.
You need to make your div reachable with the Tab key. You can accomplish this by setting the tabindex property on it. If you do not actually want people to be able to tab into that div, you can set the tabindex to -1, which will prevent people from actually tabbing to it but will otherwise set the element up for tabbing and focus.
Source: http://help.dottoro.com/ljpkdpxb.php

Browsers usually have this behavior built-in,
In order to use arrow keys to scroll down your div, you must have an element within focused.
Lookup http://api.jquery.com/focus/

Related

How to find out and control which elements gets scrolling keyboard events?

HTML has scrollable elements. At any given time one of them is going to receive keyboard scrolling controls like up/down arrow, pageup/pagedown etc.
How can I find out which element is currently active in this way, and how can I make an element active in this way?
Here's jsfiddle to demonstrate the issue.
I can click on e1, e2, e3, or e4. If I do, then arrow keys will scroll that element.
The obvious way to do this would be to call element.focus(). But that does nothing when called on a scrollable div, and document.activeElement keeps pointing to body not to any of them (the one that's actually active, or the one I tried to make active).
So:
is there some other DOM thing which controls it?
or is this functionality not exposed by browsers in any way?
or do I need to set a bunch of tabindex settings to access this state through JS, even though browsers can handle active scrolling status without any tabindex by theselves?
Use Event Listeners To Do So
function gg1(){
document.getElementById("focused").innerText = "e1"
}
function gg2(){
document.getElementById("focused").innerText = "e2"
}
document.getElementById("e1").addEventListener("scroll", gg1);
document.getElementById("e2").addEventListener("scroll",gg2);
This Code Is Just The Basic Version Of How You could achieve it. You can always minify it.

Getting the current div id in content-editable div(specific)

I am recently working on one of my projects and currently i am stuck in some problem. Well, i have made a content editable div where the user can type its input. This content_editable div contains several div's in which user has to type. I tried document.activeElement but it gives me the content_editable div not the specific div and that the one with id second_div
I want to know how to find that specific div in content_editable div where user is type.For example:-
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
I am the first div
</div>
<div id="second_div">
I am the second div and i want to know if the focus is on me
</div>
</div>
My Javascript:
window.onload = function () {
getDivwhohasfocusincontentedtiablediv(); // Something like that
};
I can use jquery but only at the last choice. I want to use only javascript for this purpose.Please help me to solve this, i didn't find solution for this all the net ( it could be that i haven't searched carefully). Thanks in advance
One possible solution is to attach an Event Listener on each inner div to listen for "focus" event. However I found out that not all elements emit "focus" events.
JQuery docs says:
The focus event is sent to an element when it gains focus. This event
is implicitly applicable to a limited set of elements, such as form
elements (input, select, etc.) and links (a href). In recent
browser versions, the event can be extended to include all element
types by explicitly setting the element's tabindex property. An
element can gain focus via keyboard commands, such as the Tab key, or
by mouse clicks on the element.
Adding tabindex attribute to each inner div will make it possible to listen to focus events.
Example at JSFiddle. Note: I wrote the code in JQuery but it can easily be written in JS.
You can find focus element in js using this,
var focused = document.activeElement;
What about this ,
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
First Div
</div>
<div id="second_div">
Second Div
</div>
</div>
$(document).ready(function () {
function onMouseUp(e) {
console.log(this.id);
}
document.getElementById("first_div").addEventListener("mouseup", onMouseUp, false);
document.getElementById("second_div").addEventListener("mouseup", onMouseUp, false);
});
Demo Here JS FIDDLE
to get specific div
in Javascript you can use
document.getElementById("second_div")
or using Jquery
$("#second_div")
make sure your id was unique. This is the fastest way to find obj in any browser.
now for getting getting the active div. why not put specific event whenever the div was clicked or edited. like:
$("#second_div").click (function (){
//raise flag or something
currentDiv = "second_div";
})
function getCurrentDiv()
{
//do something in currentDiv
}
or try also explore other event such as, on mouse over, on mouse leave, etc.
i hope that might help. other wise, please elaborate your question if I missed something.

page scrolls down when clicking href=#SomeDivName

I'm using Twitter's Bootstrap topbar.
When I click on some navigation href
href=#SomeDivName
Like when you press the navigation in this page:
http://twitter.github.com/bootstrap/examples/fluid.html#contact
The page scrolls down a bit.
I want the relevant section will appear after clicking,
but I don't want the page to scroll down.
$('a[href="#SomeDiveName"]').on('click', false);
This will return false when you click on the anchor tag with an href attribute set to #SomeDiveName. Which will prevent the default behavior of the element, which in this case is to scroll to the element to which the href attribute refers.
If you have a set of these links then I'd suggest adding a class to identify them so you can select them all at once:
$('.stop-this-link').on('click', false);
This will prevent the default behavior for all elements with the stop-this-link class whenever the element is clicked. Selecting by class is a lot faster than by attribute too. When searching by attribute, every element in the DOM must be checked.
Note that returning false in a jQuery event handler is the same as calling: event.preventDefault() and event.stopPropagation().
For more info about these functions see here:
event.preventDefault(): http://api.jquery.com/event.preventdefault
event.stopPropagation(): http://api.jquery.com/event.stoppropagation
instead of using <a href="#target"> use <a data-target="#target"> and remove the href attribute
Jasper's answer is correct, however you might get some weirdness if you bind other things later. I tend to use this:
$('.stop-this-link').on('click', function(e){ e.preventDefault() });
Essentially the same thing, but importantly it does not stop propagation of the event up the DOM, at the cost of being slightly more verbose.

What is the right href value for a JavaScript anchor tag?

I usually have to bind a JavaScript function to an anchor-click event. That is easy using jquery or the onclick inline attribute.
But, my problem is that I never know what the best way to keep href empty is.
For instance:
<a href="javascript:void(0)"> - It seems like a bit too much code for just being empty
<a href=#> - If I don't want to move to another page, I must return
false in the JavaScript call
<a href> - This option breaks the
cursor and hover style and the browser doesn't render it as a link
<a> - idem
What is the best href value for empty anchors? I'm not interested to keep functionality without JavaScript
The right one is to use an empty a element href attribute and bind the click event in Javascript.
For unobtrusive design, you should have a href attribute with a proper link (so those without Javascript can still use the site) and remove the attribute in Javascript, binding the click event.
If you are simply using the a element as a target to bind the click event to, consider using a div or span instead.
I'm personally a firm believe in using JavaScript to extend functionality, not replace. With that said, I leave anchors pointing to a "safe" fall-back of the action I'm really just executing with javascript. Simply put:
Then, supplement (and return false) if javascript was able to successfully load and bind to the element, otherwise still provide the user the ability to accomplish the task if they don't have javascript (either blocked via plugin or just not loaded).
Simply do not use A element. You can as well make DIV clickable or any other element.
Or you can also simply leave href attribute out, like so.
<a onclick="myFunction();">dasd</a>
If you also want to look it like a link, put this in CSS:
a {
text-decoration: underline;
color: blue;
}​
I think
or
is the best way to indicate empty anchor.
and
will move the page to the dom element which has id="someId"
it all depends. if you are clicking an anchor to open a panel on the page then I am happy to use option 2 but only if I insert that anchor with javascript.
this then means with javascript disabled the anchor doesn't show and the panel should be visible.
if the link goes somewhere then you need the actual link address like brad christy and odid said.
<a href=#>ABC</a>
=> on click of above link it will set url in address bar which makes flickering of document or resetting scroll position
to avoid above problem,
<a href=# onclick="return false" >abc</a>
can be used and bind event handler using jQuery as usual
or you can execute any function on onclick which return false value.

How can I make a sortable, changeable, addable, removable web-page element?

I'm creating a web-app interface which will allow users to construct sentences by clicking on words/phrases. Each word of phrase will be contained in its own page element, eg. a <div>. So the div class would need to allow:
dragging into a different order relative to the other divs/words (ie. sorting)
an X (only visible when hovering over) in the top right corner of its box to remove it completely upon clicking
changing of font/text upon click actions
be inserted into the page when the user wishes to add another word
For instance, imagine this is the page (quote marks denote an element):
"Hi, my name is" [Textbox] "I work at..." "and I was born in" [Combobox]
The phrase in italics is 'inactive' and not part of the sentence, but if the user clicked it then it would change to "I work at" [Textbox] and a new div would be added eg. "And also at..." to allow further expansion. The phrases in bold would have a close button /clickable action to get rid of them or make them inactive again. Also they would be draggable to change the order. As you can see I would also need to dynamically insert new textboxes and comboboxes to accommodate more phrases requiring input.
Could somebody give me a brief run down on what steps I need to take? I've seen sortable list elements in JQuery eg. http://jsfiddle.net/ctrlfrk/A4K4t/ which is a start. Would I just need to spruce this up with some basic JavaScript and CSS? Or would I need to use server-side scripting to dynamically add more page content?
To summarize, I need the div to change font/text upon clicking, have a hover-over close button, remove and be inserted upon simple click events, and be sortable by dragging. I also need comboboxes/textboxes to be added/removed in parallel.
Any tips would be greatly appreciated.
You don't need the server for new content unless it is stored or generated there.
Not having done this exact thing before I don't see any grand scheme to implement, I would just add the features incrementally until you get where you need to go. You may have to refactor things a bit along the way, but I probably don't have to tell you that. ;)
One thing you will have to do when you add or delete elements is to rebind the jQuery functions, it won't enough to just call them when the document loads. So put them in a function and call it whenever you add or remove an element.
Regarding your description of the UI behavior, you say that inactive elements can be dragged and that they can be made active by clicking on them. You can do this (just see if the thing has been dragged or not on mouseup to know whether it was drag or a click) but it might not be the best UI design choice, IMO. It wouldn't be the worst thing in the world, but I find it a little frustrating when the wrong thing happens when I try to do something. Of course, implementing and seeing for yourself is probably best.
Sorting:
I would implement the phrases in an unordered list (ul) which makes it as simple as
$("#ulId").sortable();
You can make ul/li items stack next to each other in a similar manner to how you make horizontal navigation menus out of ul elements.
A destrunction button:
Just use a template li similar to this
<li id="text1Wrapper">
<span id="text1"
onmouseover="javascript:$('text1Remove').fadeIn();"
onmouseout="javascript:$('text1Remove').fadeOut();"
onclick="javascript:$('text1Content').
replaceWith(
$(document.createElement('input'))
.attr('type','text')
.val($('text1Content').text())
);">
<span id="text1Content">Text Here</span>
<img id="text1Remove"
style="display: none;"
src="./x.jpg" alt="Remove"
onclick="javascript:$(this).parent().remove();"
/>
</span>
</li>
A quick description:
The span mouse over event tells jquery to fade in the remove button (so when you hover, the remove button becomes available).
The span mouse out event tells jquery to fade out the remove button when it's no longer needed (so when you move the mouse off the li, the remove button is no longer visible)
The onclick of the span replaces the span with a text box containing the content of the span. I will leave the "save changes" as an excercise for the reader, since it's essentially the same but in reverse.
Img tag style has display: none to hide it initially. This is essentially the end product of a fadeOut() but without the fade.
The on click event of the remove button gets the parent (the li) and removes it, and all children from the dom.
Note that the events are only put here because it seemed the logical place to explain it. All events in the outer SPAN tag are a useless waste of space, as they will all be overridden when we clone the node in the next section.
Insertion into the page:
All you have to do now is
var cloneLi = $('#text1Wrapper').clone();
cloneLi.attr('id', 'text2Wrapper');
var cloneSpan = cloneLi.children('#text1').attr('id', 'text2');
var cloneContent = cloneSpan.children('#text1Content').attr('id', 'text2Content');
var cloneRemove = cloneSpan.children('#text1Remove').attr('id', 'text2Remove');
You will then need to change the mouseover, mouseout and onclick functions of the outer span using jquery events:
cloneSpan.mouseover(function(e) {
// Insert functionality from template here
});
cloneSpan.mouseout(function(e) {
// Insert functionality from template here
});
cloneSpan.click(function(e) {
// Insert functionality from template here
});

Categories