javascript get text at mose postion - javascript

How can I get text at mouse position?
I have now some like this
document.body.onmousemove = function(){
//todo:Get text at mouse position
}

One way of doing so is using [PrototypeJs][1]
Try this one let me know if there is any problem
$(document.body).observe('click', respondToClick);
function respondToClick(event) {
var element = event.element();
var source = element.innerHTML;
}

Related

How to fix reverse text in javascript live syntax highlighting?

My script highlights the keywords but whenever it does, it messes with the string and does random things with the text like reverse it and mix it up.I was wondering if someone could tell me how to unreverse this text or move the cursor to the end of the contenteditable div or at most just fix it for me. I don't want any external libraries just javascript and jquery.
jsfiddle
JS Code:
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
elem.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
elem.innerHTML = code;
}
setInterval(Color,1000)
Thanks!
If the issue you're having is the cursor moving around while editing, you can fix that by grabbing the position of the cursor and putting it back at the end of the function. Do that by getting the selectionStart property of your editor textbox and then setting the selectionEnd property to that value after running the replacement.
Check out this answer for more information about selectionStart and selectionEnd.
Here's a simple code snippet from this answer that should get you rolling.
document.getElementById('target').addEventListener('input', function (e) {
var target = e.target,
position = target.selectionStart; // Capture initial position
target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.
target.selectionEnd = position; // Set the cursor back to the initial position.
});
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />
This issue is coming as the textContent of editor id being equated to its innerHTML. So change the variable name like the JS code I was written here :
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
var elem2;
elem2.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
var elem2;
elem2.innerHTML = code;
}
setInterval(Color,1000)

Getting an images position within a ul javascript

I'm trying to get the position of an image with an a ul for example:
function myFunction(){
var img = document.getElementById("myID").querySelectorAll("img");
var x = x;
img[x].style.backgroundColor = "red";
}
The function will be ran when someone clicks the image.
I want a way to get var x = the number of the image that was clicked on.
I don't know jQuery So i'd appreciate if it was all in plane javascript thanks.
Thats an x y problem. Probably:
//wait for all clicks
window.addEventListener("click",function(event){
//check if it has a parent with id myID
var e=event.target;
while(e!==document.body && e.id!="myID"){
e=e.parent;
}
if(e.id=="myID"){
//set a backgroundcolor to the clicked element. May also check if Node is IMG
event.target.style.backgroundColor="red";
}
});

Append HTML Tag Into Codemirror and Center Cursor Location

Fiddle - http://liveweave.com/kzBlq3
I'm trying to add custom html tags into CodeMirror and focus the cursor into the center of these tags.
Here's an example of how it'd be done for a textarea.
// Mirror Codemirror Code to Textarea
$(".code").val( editor.getValue() ).on('keyup change', function() {
editor.setValue( $(this).val() );
});
// Add center code
$(".bold").click(function() {
// For a regular textarea & center cursor
var start = $('.code').get(0).selectionStart;
$('.code').val($('.code').val().substring(0, start) + "<strong></strong>" + $('.code').val().substring($('.code').get(0).selectionEnd));
$('.code').get(0).selectionStart = $('.code').get(0).selectionEnd = start + 8;
$('.code').focus();
return false;
});
The lines and locations will always be different so I have to grab it's location first before I add and move it aside the added characters as I did with the textarea demo.
However I don't want to use a blank textarea. I want to use Codemirror.
I can add the html tag without a problem, but getting the cursor location inside of the appended tag is where I'm having trouble.
editor.replaceRange("<strong></strong>", editor.getCursor());
Add the following code to move cursor to center of tag. Also I updated your code, Please use the below link for accessing it
http://liveweave.com/LLq9GS
$(".bold").click(function() {
// For codemirror & center cursor
editor.replaceRange("<strong></strong>", editor.getCursor());
editor.focus();
var str="</strong>";
var mynum=str.length;
var start_cursor = editor.getCursor(); //I need to get the cursor position
console.log(start_cursor); //Cursor position
var cursorLine = start_cursor.line;
var cursorCh = start_cursor.ch;
//Code to move cursor back [x] amount of spaces. [x] is the data-val value.
editor.setCursor({line: cursorLine , ch : cursorCh -mynum });

How can I best make an inline span draggable within a paragraph of text?

I have a paragraph of text in which the user may place a "pin" to mark a position. Once a pin has been placed, I would like to allow the user to move its position by dragging it to a new location in the paragraph. This is simple to do with block elements, but I have yet to see a good way to do it with inline elements. How might I accomplish this?
I have already implemented it using window.selection as a way to find the cursor's location in the paragraph, but it is not as smooth as I would like.
As a note, I am using the Rangy library to wrap the native Range and Selection functionality, but it works the same way as the native functions do.
Here is the code:
$(document).on("mousedown", '.pin', function () {
//define what a pin is
var el = document.createElement("span");
el.className = "pin";
el.id = "test";
//make it contain an empty space so we can color it
el.appendChild(document.createTextNode("d"));
$(document).on("mousemove", function () {
//get the current selection
var selection = rangy.getSelection();
//collapse the selection to either the front
//or back, since we do not want the user to see it.
if (selection.isBackwards()) {
selection.collapseToStart();
} else {
selection.collapseToEnd();
}
//remove the old pin
$('.pin').remove();
//place the new pin at the current selection
selection.getAllRanges()[0].insertNode(el);
});
//remove the handler when the user has stopped dragging it
$(document).on("mouseup", function () {
$(document).off("mousemove");
});
});
And here is a working demo: http://jsfiddle.net/j1LLmr5b/22/ .
As you can see, it works(usually), but the user can see the selection being made. Have any ideas on how to move the span without showing the selection highlight? I will also accept an alternate method that does not use the selection at all. The goal is to allow movement of the span as cleanly as possible.
You can do this using ranges instead using code similar to this answer. Unfortunately the code is a bit longer than ideal because IE hasn't yet implemented document.caretPositionFromPoint(). However, the old proprietary TextRange object, still present in IE 11, comes to the rescue.
Here's a demo:
http://jsfiddle.net/j1LLmr5b/26/
Here's the relevant code:
var range, textRange, x = e.clientX, y = e.clientY;
//remove the old pin
$('.pin').remove();
// Try the standards-based way first
if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse();
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
// Finally, the IE way
else if (document.body.createTextRange) {
textRange = document.body.createTextRange();
textRange.moveToPoint(x, y);
var spanId = "temp_" + ("" + Math.random()).slice(2);
textRange.pasteHTML('<span id="' + spanId + '"> </span>');
var span = document.getElementById(spanId);
//place the new pin
span.parentNode.replaceChild(el, span);
}
if (range) {
//place the new pin
range.insertNode(el);
}
Try this my friend
el.appendChild(document.createTextNode("d"));
You have create empty span tag that's why you found empty.
add after
el.id = "test";
this
var value = $('.pin').text();
$(el).text(value);
You can hide selection with css
::selection {color:red;background:yellow;}
::-moz-selection {color:red;background:yellow;}
that's all how i can help for a now

Scrolling up and down in the TextArea

Is there any specific function for scrolling up and scrolling down in the TextArea. "onscroll" triggers when scrolling up/down happens in the TextArea.
Also, how to go to the new line after the last line in the text area and put "dash"(--) when clicking(scrolling) down. Thanks.
I might be wrong but as I understand it you're after a function that actually programmatically scrolls the textarea for you. If this is correct the following works:
var scrollUp = function(elementId) {
"use strict";
var element = document.getElementById(elementId);
element.scrollTop = 0;
};
var scrollDown = function(elementId) {
"use strict";
var element = document.getElementById(elementId);
element.scrollTop = element.scrollHeight;
};
See jsFiddle example here: http://jsfiddle.net/WnHpj/3/
You can of course use scrollTop to move the scroll in smaller increments if that is what you wish.
I don't really understand what you are looking for with your last question, please explain further if you still want help with that.
EDIT
The dashes... add this function:
var addDashes = function(elementId) {
"use strict";
var element = document.getElementById(elementId);
if(element.value.substring(element.value.length - 4, element.value.length) !== "\n--\n") {
element.value = element.value + "\n--\n";
element.focus();
}
};
See the updated jsFiddle example: http://jsfiddle.net/sQVe/WnHpj/7/
Hope that is what you wanted.
$("#textbox").scroll(function(e){
//this happens when there is a scrolling action in your element
})

Categories