How to replace dot(.) into special character "।" on only dot(.) keypress - javascript

I to replace dot(.) into special character "।" on only dot(.) keypress.
I don't have much knowledge of coding.
I found a function, but when I paste a text file in the text area, it replaces all dots that are present in a text file into special characters "।".
If I am wrong, please edit or suggest the appropriate code in the code.
<!doctype html>
<html dir='ltr' lang='en-GB'>
<head>
<meta charset="UTF-8">
<title>test page</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$('textarea').on("keyup", function(e) {
var val = $(this).val();
var str = val.replace('.', '।');
$(this).val(str);
});
});
</script>
</head>
<body>
<textarea></textarea>
</body>
</html>

To replace last . just key in. It does not handle the case when pressing dot and hold.
$(function() {
$('textarea').on("keyup", function(e) {
if (e.key === '.') {
const index = this.selectionStart;
const text = $(this).val();
if (index > 0 && text.charAt(index - 1) === '.') {
$(this).val(text.substr(0, index - 1) + '|' + text.substr(index));
this.selectionStart = index;
this.selectionEnd = index;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>

Replacing the last character if the input was a dot should fix it:
$(this).val($(this).val().replace(/.$/,"|"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
jQuery.fn.extend({
insertAtCaret: function(insert) {
var el = this[0]; // get DOM element instead of jQuery object
if (document.selection) {
// IE
sel = document.selection.createRange();
sel.text = insert;
} else if (el.selectionStart || el.selectionStart == '0') {
// other browsers
var startPos = el.selectionStart;
var endPos = el.selectionEnd;
el.value = el.value.substring(0, startPos) + insert + el.value.substring(endPos, el.value.length);
el.setSelectionRange(endPos + insert.length, endPos + insert.length); // put the cursor at the end of the inserted text
} else {
// last resort, shouldn't ever get here
this[0].value += insert;
}
}
})
$(function() {
$('textarea').on("keydown", function(e) {
if(e.key==='.'){
e.preventDefault();
$('textarea').insertAtCaret("|");
//$(this).val($(this).val().substring(0, $(this).val().length - 1)+'|');
}
});
});
</script>
<textarea></textarea>

Related

Format color while typing in textarea or pre

I'm trying to create a comments section that lets users #someone. When the user types #random and then space, I want it to be highlighted. So I've created something that searches and replaces the string, but I then when the html is replaced, it places the cursor at the beginning. Any way to solve this? Any other way of doing something like this?
$('#textarea').keyup(function() {
txt = this.innerText.split(" ")
new_txt = this.innerText
for (var i = txt.length - 1; i >= 0; i--) {
if (txt[i].startsWith('#') == false) {
delete txt[i]
}
}
txt = txt.sort().join(" ").trim().split(" ")
console.log(txt)
if (txt.length > 0 && txt[0] != "") {
for (var i = 0; i < txt.length; i++) {
new_txt = new_txt.replace(txt[i], '<mark>' + txt[i] + '</mark>')
}
$('#my_console_log').text(new_txt)
this.innerHTML = new_txt
}
});
pre {
border: solid black 1px;
}
mark {
background: blue;
color: red;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<title>Test page</title>
<form>
<pre id='textarea' contentEditable='true'></pre>
<div id="my_console_log"></div>
</form>
Here is a simple plugin available which can be useful to you,
Download the plugin and edit the file jquery.hashtags.js and remove the condition for #. You can also change the style as per your requirement.
(function($) {
$.fn.hashtags = function() {
$(this).wrap('<div class="jqueryHashtags"><div class="highlighter"></div></div>').unwrap().before('<div class="highlighter"></div>').wrap('<div class="typehead"></div></div>');
$(this).addClass("theSelector");
autosize($(this));
$(this).on("keyup", function() {
var str = $(this).val();
$(this).parent().parent().find(".highlighter").css("width",$(this).css("width"));
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g) && !str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([\u0600-\u06FF]+)/g)) {
// Remove below condition for hashtag.
if(!str.match(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) { //arabic support, CJK support
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([_a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
// Keep this condition.
if(!str.match(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#/g)) {
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}else{
str = str.replace(/#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))#(([a-zA-Z0-9]+)|([\u0600-\u06FF]+)|([ㄱ-ㅎㅏ-ㅣ가-힣]+)|([ぁ-んァ-ン]+)|([一-龯]+))/g,'<span class="hashtag">#$1</span>');
}
}
$(this).parent().parent().find(".highlighter").html(str);
});
$(this).parent().prev().on('click', function() {
$(this).parent().find(".theSelector").focus();
});
};
})(jQuery);
Instead of replacing the html just append a class with the color that you want

how to Paragraph text come display like text typing effect

I try to display text come with typing text effect.i tried like this
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<span id="holder"></span>
</body>
<script>
(function($)
{
$.fn.writeText = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 100);
};
})(jQuery);
$("#holder").writeText("This is some text");
</script>
</html>
It's work but i need display Paragraph content like this but now to call Paragraph content in writeText.
If it's not good way to display Pragraph like typing effect. Please tell me how to solved my problem .Please give me any idea.
Thanks in Advanced.
i have simply modified your code for this, you just need get the content of each para and pass each para to your writeText function()
Just give class="effect" to to be animated
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<span id="holder"></span>
<p class="effect">Hi, this is Gokul Praveen' PARA 1!</p>
<p class="effect">Hi, this is James Bond's PARA 2!</p>
</body>
<script>
(function($)
{
$.fn.writeText = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 100);
};
})(jQuery);
$(".effect").each(function(index) {
var text = $( this ).text();
$(this).empty();
$(this).writeText(text);
});
//$("#holder").writeText("This is some text");
</script>
</html>
Execute the code in a browser and check. Don't forget to mark it correct!
I think this fiddle will do the trick
Js Fiddle
$.fn.typer = function (text, options) {
options = $.extend({}, {
char: ' ',
delay: 1000,
duration: 600,
endless: true
}, options || text);
text = $.isPlainObject(text) ? options.text : text;
var elem = $(this),
isTag = false,
c = 0;
(function typetext(i) {
var e = ({
string: 1,
number: 1
}[typeof text] ? text : text[i]) + options.char,
char = e.substr(c++, 1);
if (char === '<') {
isTag = true;
}
if (char === '>') {
isTag = false;
}
elem.html(e.substr(0, c));
if (c <= e.length) {
if (isTag) {
typetext(i);
} else {
setTimeout(typetext, options.duration / 10, i);
}
} else {
c = 0;
i++;
if (i === text.length && !options.endless) {
return;
} else if (i === text.length) {
i = 0;
}
setTimeout(typetext, options.delay, i);
}
})(0);
};
$('#foo').typer(['<i>Anyone</i> <u>is</u> <b>awesome</b>!', 'Foo bar.', 1337]);

Change an image when input is given

I have a small basic html code with JavaScript . All I want is when I type 3,it should show me an image as specified and for 9 accordingly. This is the demo. Visit http://jsbin.com/UVOFeGIG/1/edit
Its working there. I don't know why the JavaScript doesn't work this way. Can anyone figure this out?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
var num2img = {
"3":"visa",
"9":"mastercard"
};
$('#num').on('input', function(){
var val = this.value;
if(val.length<=1){
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png';
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
</script>
<meta charset=utf-8 />
<title>Demo by Roko C.B.</title>
</head>
<body>
<input id="num"><br>
<img id="cardImage" src="http://placehold.it/100x100/cf5">
</body>
</html>
Try this
$(document).ready(function(){
var num2img = {
"3":"visa",
"9":"mastercard"
};
$('#num').keyup(function(){
var val = this.value;
if(val.length<=1){
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png';
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
});
DEMO
try something like this
$(function(){
// you have not given any event
$('#num').on('keyup', function(){
var val = this.value;
if(val.length){//your length checking logically wrong
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
})
You need to change the $('#cardImage')[0] to $('#cardImage').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png'); as # will return one element replace See the jsfiddle http://jsfiddle.net/mailtoshebin/dMWmw/
var num2img = {
"3":"visa",
"9":"mastercard"
};
$('#num').on('input', function(){
var val = this.value;
if(val.length<=1){
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png');
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
try capturing "keypress" event on input box, http://api.jquery.com/keypress/ OR
try capturing "change" event on input box, http://api.jquery.com/change/
Place you script code inside
$(document).ready(function(){
//your code goes here
});
and replace
$('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';
by
$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.gif';

How do I send textbox values to javascript function?

I seem to be doing something wrong here. This script works with the prompts, which have been commented out, but not with the textboxes. Am I somehow failing to send the input values to the function?
I'm also having trouble using regular expressions in the if-statements, rather than a clumsy list of punctuation marks.
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<label>Say what you want typed</label>
<input class="textBox" id="userInput" />
<label>A pregnant pause... (300?)</label>
<input type="number" id="userBreath" />
<button onclick="printLooper()" href="javascript:;">Submit</button>
<! --input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" --/>
<script type="text/javascript" language="javascript">
var myString = document.getElementById('userInput').value;
//var myString = prompt('Say what you want to see typed','Right here, baby'); //prompts are annoying, i know
//var myDelay = prompt('Type speed (try 50)', 'The higher the number, the slower it types');
//var myBreath = prompt('Now tell me how long to pause at each breath (shift+2)', 'Try 300')
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
var loopTimer;
function printLooper(){
if(myArray.length > 0 ){
var char = myArray.shift();
if ( char === '#'){
document.getElementById("myTypingText").innerHTML
}else {
document.getElementById("myTypingText").innerHTML += char;
}
} else {
clearTimeout(loopTimer);
}
if (char === ' '){
loopTimer = setTimeout('printLooper()', 20);
} else if (char === ',' || char === '.' || char === '?') {
loopTimer = setTimeout('printLooper()', 220); //fiddle with these 2nd params as you see fit
} else if (char === '#'){
loopTimer = setTimeout('printLooper()', myBreath);
} else {
loopTimer = setTimeout('printLooper()', 47);
}
}
printLooper();
</script>
</body>
</html>
Any help appreciated!
You need to have some variables inside your function.
I made a demo and removed the inline js on the button.
Use this if useful:
<button id="sub_btn">Submit</button>
var loopTimer;
var char, myString, myBreath, myArray;
function printLooper() {
if (myArray.length > 0) {
char = myArray.shift();
console.log(char);
if (char === '#') {
document.getElementById("myTypingText").innerHTML = '';
} else {
document.getElementById("myTypingText").innerHTML += char;
}
} else {
clearTimeout(loopTimer);
return false; // To the loop will stop when the array is empty
}
if (char === ' ') {
loopTimer = setTimeout(printLooper, 20);
} else if (char === ',' || char === '.' || char === '?') {
loopTimer = setTimeout(printLooper, 220); //fiddle with these 2nd params as you see fit
} else if (char === '#') {
loopTimer = setTimeout(printLooper, myBreath);
} else {
loopTimer = setTimeout(printLooper, 47);
}
}
document.getElementById('sub_btn').onclick = function () {
myString = document.getElementById('userInput').value;
myBreath = document.getElementById('userBreath').value;
myArray = myString.split("");
printLooper(myString, myBreath, myArray);
};
Demo here
This syntax has extra characters you probably typo'd in there. I also have never seen a button element with the href attribute before but I don't get out much. You might want to revisit this.
<button onclick="printLooper()" href="javascript:;">Submit</button>
You should put these lines inside the function
var myString = document.getElementById('userInput').value;
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
It's empty because you put it outside the function and initially the inputs are empty and inside the function if(myArray.length > 0 ) is always false, you need to populate the array once the function is called after the button pressed and also href is not a valid attribute for button as another answer stated it.
var myString = document.getElementById('userInput').value;
//var myString = prompt('Say what you want to see typed','Right here, baby'); //prompts are annoying, i know
//var myDelay = prompt('Type speed (try 50)', 'The higher the number, the slower it types');
//var myBreath = prompt('Now tell me how long to pause at each breath (shift+2)', 'Try 300')
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
Move these inside the function.

How to send Keyboard events (e.g. Backspace, Delete) in Safari from Javascript

I'm implementing an on-screen Keyboard for a Javascript application. The text should appear in a textarea-Element. I've no problem creating text-events but feel unable to create non-text events such as the Backspace. Here is some sample code:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function log(text) {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML += "<br/>" + text;
}
}
function logEvent(e) {
log("Type: " + e.type + ", which: " + e.which + ", keyCode: " + e.keyCode + ", charCode: " + e.charCode + ", keyIdentifier: " + e.keyIdentifier + ", data: " + e.data);
}
function logClear() {
var elem = document.getElementById("log");
if (elem) {
elem.innerHTML = "";
}
}
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("KeyboardEvent");
ke1.initKeyboardEvent("keydown", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// how to set "keyCode" and "which"?
// 1. ke1.keyCode = 8; will be ignored due to "writable: false"
// 2. delete ke1.keyCode will be ignored too
// and Object.defineProperty(KeyboardEvent.prototype, "keyCode", ... whatever ...);
// will result in Exception due to "configurable: false"
// 3. generating a more general Event (e.g. "var e = document.createEvent("Events");")
// and setting all necessary props (e.g. "e.initEvent("keydown", true, true);e.keyCode=8;e.which=8;")
// will work, but the textarea will ignore the Event
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("KeyboardEvent");
ke2.initKeyboardEvent("keyup", true, true, window, "U+0008", 0, ""); // U+0008 --> Backspace
// same question as above
textarea.dispatchEvent(ke2);
}
function init() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", logEvent, false);
textarea.addEventListener("keypress", logEvent, false);
textarea.addEventListener("keyup", logEvent, false);
textarea.addEventListener ("textInput", logEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
<button onclick="logClear()">clear log</button><br/>
<div id="log"></div>
</body>
</html>
The interesting function here is sendBackEvent(). I tried hard to get exactly the same event like pressing the Backspace-Button on the physical Keyboard but didn't succeed.
I know there is a Webkit-Bug but hoped there could be some other way to get this working. Has anyone had the same problem? Could it be solved? How? The proposed solution here (calling new KeyboardEvent(...) ) doesn't work because directly calling the KeyboardEvent constructor results in following exception:
Exception: TypeError: '[object KeyboardEventConstructor]' is not a constructor (evaluating 'new KeyboardEvent(...)')
I have no more ideas.
Since there seem to no way out, i found myself constrained to install my own backspace event handler. The working code (without logging now) is here:
<html>
<head>
<title>Test Textarea Events</title>
<script type="text/javascript">
function sendBackEvent() {
var textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
var ke1 = document.createEvent("Events");
ke1.initEvent("keydown", true, true);
ke1.keyCode = ke1.which = 8; // Backspace
textarea.dispatchEvent(ke1);
var ke2 = document.createEvent("Events");
ke2.initEvent("keyup", true, true);
ke2.keyCode = ke2.which = 8; // Backspace
textarea.dispatchEvent(ke2);
}
function handleBackEvent(e) {
if(e.keyCode != 8) {
return;
}
if (textarea.value.length == 0) {
return;
}
var text = textarea.value;
var selectionStart = textarea.selectionStart;
var selectionEnd = textarea.selectionEnd;
if (selectionStart < selectionEnd) {
var text1 = (selectionStart > 0 ? text.slice(0, selectionStart) : "");
var text2 = (selectionEnd < text.length ? text.slice(selectionEnd) : "");
textarea.value = text1 + text2;
}
else if (selectionStart > 0) {
var text1 = (selectionStart - 1 > 0 ? text.slice(0, selectionStart - 1) : "");
var text2 = (selectionStart < text.length ? text.slice(selectionStart) : "");
textarea.value = text1 + text2;
selectionStart--;
}
textarea.selectionStart = textarea.selectionEnd = selectionStart;
e.preventDefault();
e.stopPropagation();
return false;
};
var textarea;
function init() {
textarea = document.getElementById("textarea");
if(!textarea) {
return;
}
textarea.addEventListener("keydown", handleBackEvent, false);
}
</script>
</head>
<body onload="init()">
<textarea id="textarea" name="text" cols="100" rows="20"></textarea><br/><br/>
<button onclick="sendBackEvent()">send BackEvent</button>
</body>
</html>
Just in case someone else run into same trouble.

Categories