Check when an element has been selected/tabbed onto - javascript

I have an HTML page where I have a few divs with contenteditable="true". I also set the tabindex sequentially so when the user hits tab he or she will go through all of the editable divs. However, right now I have "Insert notes here" written inside each of the divs (see below).
<div contenteditable="true" tabindex='1'>Insert notes here<div>
<div contenteditable="true" tabindex='2'>Insert notes here<div>
<div contenteditable="true" tabindex='3'>Insert notes here<div>
I'm trying to get rid of the "Insert notes here" text when the user tabs to the div. Right now, I'm able to get rid of the text if they click on it with the following jQuery:
function selectText(containerid) {
if(document.getElementById(containerid).innerHTML == "Insert notes here") {
document.getElementById(containerid).innerHTML = "";
}
}
Is there a way to achieve the same effect but also when the user uses tab?

sounds like you are looking for the onfocus event
http://www.w3schools.com/jsref/event_onfocus.asp
In jquery:
$("#fieldId").focus(function() {
//your code here
});

Try this working snippet
$(document).on('keyup, focus', '.editor', function(e) {
this.innerHTML = "";
//detect 'tab' key
if (e.keyCode == 9) {
//add tab
this.innerHTML = "";
//prevent focusing on next element
e.preventDefault()
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" class="editor" tabindex='1'>1
</div>
<div contenteditable="true" class="editor" tabindex='2'>2
</div>
<div contenteditable="true" class="editor" tabindex='3'>3
</div>

Related

Prevent html input focus being lost to the body tag

When I have focus on the input field and I click in any open area of the body, the body becomes the document.activeElement , Is there a way to prevent the body focus completely.
What I am looking for is :
To prevent focus the body and maintain focus on the input field.
To avoid the firing of the blur event on the input field.
I've tried adding tabindex=-1 but I believe its for Tab functionality and hence does not work in this case.
document.querySelector("#inpdontlosefocus")
.addEventListener("blur",function(){
const $log = document.querySelector("#log");
$log.innerText += "\r\nLost focus";
})
html,body {
width:100vw;
height: 100vh;
}
<body id="notokaytogetfocus">
<input id="inpdontlosefocus" type="" placeholder="dont lose focus to body">
<input id="inpokaytofocus" type="" placeholder="allow focus">
<div id="log"></div>
</body>
Here is a solution that will always keep the focus on input fields in your document:
you will be able to switch the focus between input fields.
if you clicked outside an element that is not input, it will get the lastest input blurred and will apply focus on it.
var blurred, focused;
const $log = document.querySelector("#log");
var els = document.querySelectorAll('input');
Array.prototype.forEach.call(els, function(el) {
el.addEventListener('focus', function() {
focused = this;
});
el.addEventListener('blur', function() {
$log.innerText += "\r\nLost focus;"
blurred = this;
});
});
document.addEventListener("click", function(e) {
e.preventDefault();
if (focused && focused.tagName == "INPUT") {
$log.innerText += "\r\nactiveElement= " + document.activeElement.id;
focused.focus();
} else if (blurred) blurred.focus();
})
html,
label {
width: 100%;
height: 100%;
}
<body id="notokaytogetfocus">
<input id="inpdontloosefocus" placeholder="dont loose focus to body">
<input id="inpokaytofocus" placeholder="allow focus">
<div id="log"></div>
</body>
I'd added more html elements for a more accurate demonstration, the logic here is if the event source in body is not focus-able then we set focus back to the input we want, other wise the its a focusable element thus will get the focus(e.g. button, link, input, ...); notice that click event is attached to body and clicking outside body won't have this behavior.
document.querySelector('.notokaytogetfocus').addEventListener("click",function (e){
if(e.target == document.activeElement){
console.log("focusable element");
}else{
console.log("not focusable element");
// we'll set foucs on desired input
document.querySelector("#inpdontlosefocus").focus()
}
})
.notokaytogetfocus{height: 100vh; width:100vw;}
<div class="notokaytogetfocus">
<input id="inpdontlosefocus" type="" placeholder="dont lose focus to body">
<input id="inpokaytofocus" type="" placeholder="allow focus">
<button>do!(focusable)</button>
<p>lorem ipsum</p>
<div>some text</div>
</div>

RichEditor use execCommand('bold') twice append extra <span> label

I use execCommand('bold') to make the following text bold, but when I try it again to disable bold, then add other label like 'h' or something, It add extra label link this:
<h1><span style="font-weight: normal;">111</span></h1>
I wonder how to avoid this?
It should works
First of all if you really doing it correctly, it won't happen like that.
Please see the sample below, it should works.
document.designMode = "on";
function myFunction(event) {
if (event.keyCode == 16) {
// Press shift btn exec cmd for bold trigger
document.execCommand("bold");
//check in alert box when triggered
//alert( document.getElementById("thebody").innerHTML );
//check the updated code in console once triggered
console.log( document.getElementById("thebody").innerHTML );
}
}
<!DOCTYPE html>
<html>
<body onkeydown="myFunction(event)">
<div id="thebody">
<h1>Exec execCommand("Bold")</h1>
<p>Try to exec by pressing shift btn once highlighed</p>
<h2>Again execCommand("Bold")</h2>
<p>Select some text in this page, and press the SHIFT button to make the selected text toggle between bold and normal.</p>
</div>
<div id="preview">
</div>
</body>
</html>
Note/Advise:
However, if your problem persists in your version of code, please share with me the function that trigger this exec Cmd.
javascript code is just like this:
Editor.setHeading = function(heading) {
if(heading == 0){
document.execCommand('formatBlock', false, '<div>')
} else {
document.execCommand('formatBlock', false, '<h'+heading+'>');
}
}
Editor.setBold = function() {
document.execCommand('bold', false, null);
}
html is:
<body>
<div id="editor" contenteditable="true"></div>
<script type="text/javascript" src="editor.js"></script>
</body>

How to handle click event in mouse and keyboard?

I have done
some html tags click event it's working by mouse click and
keyboard enter
some html tags click events are are not working when
press in keyboard enter. only working mouse click.
I need both are we excutue in single method
like: Button, Anchor
"Button **and Anchor**" - tags only suporting .
"p,div,span,h1"- tags are not suporting .
Button and Anchor Tag only working both mouse click and keyboard enter
!
remaining element are not working tab using keyboard enter why ?
dont't say keycode method for keyboard enter i need similar button and anchor tag
Here is the demo:
$(document).ready(function(){
$("p").click(function(){
alert("The paragraph was p.");
});
$("div").click(function(){
alert("The paragraph was div.");
});
$("span").click(function(){
alert("The paragraph was span.");
});
$("h1").click(function(){
alert("The paragraph was h1.");
});
$("button").click(function(){
alert("The paragraph was button.");
});
$("a").click(function(){
alert("The paragraph was a.");
});
});
* {
margin-bottom:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Button and Anchor Tag only working both mouse click and keyboard enter ! </h2>
<h2>remaining element are not working tab using keyboard enter ? </h2>
<br>
<br>
<p tabindex="0">Click on this paragraph.</p>
<div tabindex="0">Click on this div.</div>
<span tabindex="0">Click on this span.</span>
<h1 tabindex="0">Click on this h1.</h1>
<button> Click on this button.</button> <br>
Click on this anchor
Thanks
J.Jayaprakash
You could use the keypress event.
To determine which character was entered, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the character code.
function alertTag( tag ){
alert("The element was " + $(tag).prop("tagName"));
}
$(document).ready(function() {
$("p, div, span, h1, button, a").click(function(e) {
alertTag(e.target);
}).keypress(function(e) {
if (e.which == 13) {
e.preventDefault(); // optionally
alertTag(e.target);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p tabindex="0">Click on this paragraph.</p>
<div tabindex="0">Click on this div.</div>
<span tabindex="0">Click on this span.</span>
<h1 tabindex="0">Click on this h1.</h1>
<button> Click on this button.</button> <br>
Click on this anchor
If you want to use the same method for all the elements (while I don't see the point in doing so) you need to include e.preventDefault(). Otherwise, when pressing enter you will trigger both the click and the keypress events.
An alternative could be to force the p, div, span and h1 elements to trigger a click event when pressing enter on them:
$(document).ready(function() {
$("p, div, span, h1, button, a").click(function(e) {
alert("The element was " + $(e.target).prop("tagName"));
});
$("p, div, span, h1").keypress(function(e) {
if (e.which == 13) {
$(e.target).trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p tabindex="0">Click on this paragraph.</p>
<div tabindex="0">Click on this div.</div>
<span tabindex="0">Click on this span.</span>
<h1 tabindex="0">Click on this h1.</h1>
<button> Click on this button.</button> <br>
Click on this anchor
If you really want to do it for all the HTML tags (even when I think that's not a good idea) you can do the following.
$("body *").keypress(function(e) {
if (e.which == 13) {
$(e.target).trigger('click');
}
});
Then, all the elements will react to a enter like they do to a click. But you should really try to replace body * for a selector that covers just the elements that you want. For example, you can add the class .enterTriggersClick to the target elements and then do:
$(".enterTriggersClick").keypress(function(e) { ...

How to make box appear when text is entered into input?

I have this HTML code:
<div class="center1">
<form>
<input type="text" class="input1" autofocus="focus" />
</form>
</div>
<br><br>
<div class="center1">
<div class="box"></div>
</div>
I have added it to this JSFiddle link: http://jsfiddle.net/PDnnK/4/
As you can see there is:
INPUT FIELD
&
BOX
I want the box to appear only when text is typed in the input. How is this done?
Start the box out with display: none. Then, you can capture the keypress event for the input:
document.getElementById('myInput').onkeypress = function () {
document.getElementById('myBox').style.display = 'block';
}
Something like this with jQuery:
$("#id-of-input").change(function() { $("#id-of-box"}.css('display', 'block'); } );
or change .change to .click
Binding to "change" is usually not super-handy, since it usually doesn't fire until you tab or click away from the element.
However, polling isn't the answer either.
original answer:
http://jsfiddle.net/xNEZH/2/
super-fantastic new answer:
http://jsfiddle.net/4MhKU/1/
$('.input1').bind('mouseup keyup change cut paste', function(){
setTimeout(function(){
var hasInput = $('.input1').val() != "";
$('.box')[hasInput ? 'show' : 'hide']();
}, 20);
});
The setTimeout is because cut and paste events fire BEFORE the text is cut or pasted.

How can I detect when a text area loses focus and keep it from losing focus when a particular element is clicked?

I have a text area #ta with a list #ac-list underneath that's used for auto complete:
<div id='container'>
<textarea id="ta" name="god" rows="20"></textarea>
<ul id='ac-list' style='visibility:hidden'></ul>
</div>
When the text area loses focus, I'd like to hide #ac-list. So I call jquery's blur on the text area:
$('#textarea').blur(function () {
$('#ac-list').css('visibility', 'hidden');
})
This works, but I'd like to add the constraint that the text area shouldn't lose focus when the user clicks on #ac-list. How can I go about this?
Is this what you need? This is just a workaround. The time taken for blur on textarea and to focus on the li item varies to different computers.
HTML:
<div id='container'>
<textarea id="ta" name="god" rows="20"></textarea>
<ul id='ac-list'>
<li>dsfd</li>
</ul>
</div>
JavaScript:
var textAreaBlur = null;
$('textarea').blur(function () {
textAreaBlur = new Date();
});
var clickTimes = 0;
$("#ac-list > li").click(
function() {
if((new Date() - textAreaBlur) < 200) {
$("#ta").focus();
$(this).text("dsfd" + ++clickTimes);
}
}
);

Categories