HTML + Javascript: Detecting where in a line of text a click occurred - javascript

What's a good way to do this without wrapping each letter with <span> tags and binding onclick functions to each, or something silly like that?

if you use a textarea and style it to not look like one, you could do something like this: Inserting a text where cursor is using Javascript/jquery

I don't think that's possible as each browser renders a page different on each client. As a javascript-event is always attached to some html tag (and a text it self is not a tag but the content of this tag) you can only retrieve the tag the event occures on or every parent tag.
You could in some way determine the approx. position of the cursor by wrapping each paragraph or sentence with div||p||span, retrieve the position of the click event relative to the document, retrieve the position of the tag the event occures on relative to the document and calculate depending on the number of sibling tags and their heights the approx. line number.

Related

How to capture a click event on a buried DIV but not anything contained in the DIV when the DIV doesn't initially exist in the DOM

I have a vanilla Javascript event listener that's passing data exactly how I want it... except when I click on text that has been bolded, or italicized, or is otherwise encapsulated. Here's my test javascript:
window.onclick = function(e){
if(e.target.dataset.lb_action){
console.log(e.target.dataset);
}
}
And my HTML:
<div><div data-lb_action=99>This text works but <b>this text doesn't</b></div></div>
If I click on "This text works but" I get my expected console report: DOMStringMap(1) { lb_action → "99" }. But if I click on "this text doesn't" the DOMStringMap is empty. I believe it's picking up the (yes, I know, deprecated) Bold tag inside the DIV tag.
Remember, that entire string of HTML doesn't initially exist when the page is built. It's dynamically loaded later. Is there a way I can force the event handler to pick up the DIV I'm interested in? I hoped the IF statement would solve that problem by picking the right data out of the bubble path. But it's not working. I've tried using an IF for the DIV "id" tag, but that also doesn't work.
How can I capture the "Data-" information out of the one DIV that matters in the DOM chain when that DIV doesn't initially exist?
You can use the closest() method to find the containing div.
Since window doesn't have a dataset property, I've used conditional chaining when testing for lb_action to prevent an error.
window.onclick = function(e) {
let container = e.target.closest("div");
if (container?.dataset.lb_action) {
console.log(container.dataset);
}
}
<div>
<div data-lb_action=99>This text works but <b>this text doesn't</b></div>
</div>

strange behavior of html tags inside contenteditable div

In my project, I am trying to add HTML tag letter (< and >) dynamically to a contenteditable div. Whenever user is pressing alphanumeric character, I am appending an empty span element which is used for calculating the position of the caret in contenteditable div.
The problem is that when I type some words like following:
when <
and press a alphanumeric character like b (which calls a function to append a span element), The contenteditable div is showing just when instead of when <b.
When I inspected the element I found the contenteditable div has the following content:
when <b<span class="spanPos"></b<span>
^ strange that span is holding '</b' instead of being empty
Here is a example JSFiddle.
I am not sure how this is happening. Please tell me what should I do to evade this issue.
PS: Here I am trying to add < and >, not HTML elements like <b></b>.
As you said, you're trying to add a symbol which can be interpreted as HTML. You need to escape it or use a different way to express it as an ISO entity:
$('#btnContent').click(function(){
$('#content').html("when <b" + "<span class='spanPos'></span>");
});
http://jsfiddle.net/Dekku/jXeVW/1/
I have visit your code and found there is a <b in JS don't know by are you using that.
Use the below code:
$('#btnContent').click(function(){
$('#content').html("when" + "<span class='spanPos'></span>");
});
By removing the <b tag you will not get this. or You should properly close to it to make the code proper.
EDITED:
After visiting your new code I got the solution you should use the following code:
$('#btnContent').click(function(){
$('#content').html("when <b");
$('#content').html($('#content').html() + "<span class='spanPos'></span>");
});
If you need the details then tell me.
The problem was actually that I was appending a span element to the text whenever the user types something in to the contenteditable div to grab the position of the caret. Something like this
Hello I am he|re
^ Caret position
Then I was adding a span element in between of that text using .html() something like this
Hello I am he<span></span>re
Now whenever I add any letter which represents Html like < or >, then it was merging some of the text inside the span (as I shown above in my post).
So, I solved it by removing it just after when I get the position through span element. I followed the below steps to solve this issue for each letter pressed by the user.
//Store the .text() in a variable.
//Replace Html letters inside the contenteditable div with alphabets which has same width. (for exact positioning).
//add span to the modified text through .html()
//get the offset position of the span
//Do something with that offset position
//Remove span
//Replace the .text() inside the contenteditable div with the text which was stored in a variable.
I did these many things to solve this issue because I was using .text() everywhere else in my project code. If I change it to .html() then I must have rewritten the complete code and might also can't complete the project.
Clearly, I couldn't have done the things which were mentioned in the other answered posts. I hope this will help someone.

Javascript/jQuery substring highlighting problem

I am using Javascript to calculate the offset and length of a substring selected on my page. This gets stored somewhere and later, when I hover over the text I want to highlight certain words in it using that offset and length in jQuery. Here is the basic code used for the highlight:
content = $("#reader").html();
newContent = content.substring(0,offset)+'<font style="color: red;">'+content.substring(offset,offset+length)+'</font>'+content.substring(offset+length,content.length);
content = $("#reader").html(newContent);
Now my problem is this: the offset and length are calculated over what is displayed on the screen. The actual HTML code, however, may also contain <p> or other tags. As a result, the text that I highlight gets "shifted", depending on the amount of HTML code present.
What is the easiest way to solve this?
This is not easily solvable. You shouldn’t calculate offset and length over the text, but over the HTML, if you want to work on the HTML afterwards. However, inserting HTML tags somewhere into an existing HTML string may lead to invalid nesting. And finally, you lose state like attached event handlers if you re-insert nodes as HTML code.
use
$("#reader").text()
instead of $("#reader").html() to get the text out of your content
I'd strip tags or use DOM methods - like. .nodeType, .nodeValue.

problem with event handlers in dojo

I have a span inside which i have a achor tag.For anchor tag , i have used DojoAttachEvent,Now somwhere in my code i replace innerHTML of span as show below.
<span id ="xyz"> <a dojoAttachEvent="onmouseover:_myfunction"> txt223 </a> </span>
Now i replace text of span as follows:
var tmptxt = dojo.byId("xyz").innerHTML
dojo.byId("xyz").innerHTML = "some more txt" +tmptxt
Now after running this code the function _myfunction doesnot get called when onmoveover gets triggered.
I know that i can get away with the problem by using two spans ,one for next txt and one for anchor , but due to some css issues(i get each span on new line,its some two colum css and if i use 2 spans txt and anchor come on 2 different line which we dont want) i cant do it.
I tried to use dojo.connect , but the problem is as my span is present in some wizard the event gets triggered when am on page other then the page which is the current page of wizard.
Try this code.it may helps.
<span id ="xyz"> <a dojoAttachEvent="onmouseover:_myfunction();return true;"> txt223 </a> </span>
First of all, if this isn't inside a widget template, dojoAttachEvent isn't what you want - you probably want something more like onMouseOver="_myfunction();".
Secondly, if you're replacing the innerHTML of the parent node of the node in question with the event, then naturally you're going to end up clobbering that node out of existence, and the event along with it, and you'd have to hook it up again one way or another. Is there a reason you can't be more careful with your DOM manipulation? Like, put an id on the a tag (or query for it from the span) and change only that node's innerHTML?

set cursor on a div element?

How do I set the cursor on a div-element in javascript?
I have a form(div-element not input) with a textstring attached on it. I want the textstring removed and the cursor set at the beginning of the element onclick.
I have removed the content in the div-element with onclick event with: divElement.innerHTML = '';
Now I want the cursor to be set?
If you mean the mouse pointer, use the CSS cursor style like this:
#mydiv {
cursor: help;
}
There are a whole load of standard options you can use. You can also define a graphic to use as the pointer (though this has cross-browser compatibility issues).
See this page on Quirksmode for more info.
Similarly, if you want to do it dynamically in Javascript, then just set the object's style:
document.getElementById('mydiv').style.cursor = 'help';
If by 'cursor', you mean the text cursor (aka the caret), I presume what you're really asking is how to make a div into an editable content box.
What you need is to set the contentEditable attribute on your div.
If you want it editable from the start, just include it in your HTML code:
<div contentEditable="true">....</div>
If you want to switch it on/off, you can set it in javascript:
mydiv.contentEditable="true"
However, the only time I can think of when it's better to use contentEditable rather than a textarea is if you're writing a WYSIWYG HTML editor.
Most of the rest of the time I would say it's probably preferable to use a <textarea>. You can style it to look like the rest of your page, and you can make it readonly or disabled when you don't want it changed. But it is much easier to work with in a form and in Javascript. The problem with using a div is that it can contain other html tags, which may affect how it works, and will likely open you up to security problems if you make it directly editable.
divElement.style.cursor = 'whatever';
If you want to move the cursor to be over the divElement, then you can't.

Categories

Resources