jquery - javascript - project for fine art school - javascript

I am a (french) student in a fine art school, and I make a project about memory in this project, the computer needs to forget the text that you write...
I know html and css but I just began javascript...
I need to change or to erase randomly some letters (or some words) in a text area; like you write your text normally, and when you have written 5 lines of text, the first line begins to change: some letters change (A became F or M) or some are erased...and the text means nothing. But the writers musn't see the change, it has to be very discreet (with a slow change of opacity or something like that.)
Thank you for your help!

Welcome to SO! Your project sounds interesting. On SO we ask that your questions be specific. You have received a couple of down votes because your question is open ended. So to help you get started I will give you these thoughts.
You can't run animation effects in a textarea. You can certainly change the content, but doing so while a user is typing probably wouldn't work very well.
That being said, perhaps the user could type in a text area, but the actual content gets copied into a div somewhere else.
Animation effects need to take place on elements. To fade out individual letters you have to wrap them in a span.
This is actually pretty complex, so try and ask your questions piece by piece on SO. Start with your main question, and then provide a short paragraph about what you are trying to accomplish.
Here are some basics that will hopefully help you get started.
http://jsfiddle.net/6Btxb/
<div id="content"> </div><br />
<input type="text" /><br />
Key Pressed: <div id="keycode"></div>
<button>Fade out and change a letter</button>
$('input').keyup(function(e) {
//in javascript you are returned a keycode as opposed to the actual
//letter pressed. So to work with all languages
//I monitor keyup instead. But this means you have to clear the textarea as
//the user types
//show the keycode of the pressed key
$('#keycode').html(e.keyCode);
//append the typed letter to the content div
//do you need to handle delete / cut and paste?
$('#content').append('<span>' + $(this).val() + '</span>');
//clear textbox
$(this).val('');
});
$('button').click(function() {
//find how many spans are in the content div
var spanCount = $('#content span').length;
//get the index of a random letter
var randomNum = randomFromTo(0, spanCount);
//create a random letter
$('#content span').eq(randomNum).fadeOut(1000, function() {
//this is a callback to the fade out animation
//change the letters value
$(this).html(randomLetter());
//fade back in
$(this).fadeIn(1000);
});
});
//generate random number between
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function randomLetter() {
var letters = 'abcdefghijklmnopqrstuvwxyz';
return letters [Math.floor(Math.random()*letters .length)];
}

Related

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

Is there a way to place a keyboard shortcut inside an editable div?

For example, i have a div which users can type into it. i would like to place shortcuts so when the user inputs the word pi. The output would be the symbol π. Or if the user inputs sqrt then they would get this symbol inf then the output would be ∞. and even when the tab button is clicked to indent a couple of lines. I have not seen a web app that does this yet so any help would be appreciated.
There's some extensive key tracking + field updating you can do to accomplish this, or you can get a jQuery plugin that already does something similar (if not exactly) and modify it to accomplish the same task.
This might be what you are looking for though:
http://code.google.com/p/js-hotkeys/wiki/about
You could simply use a replace. See JSFiddle demo here
$('.test').keydown(function (event) {
if ($('.test').val().contains("pi")) {
var newVal = $('.test').val().replace("pi", "π");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
else if ($('.test').val().contains("inf")) {
var newVal = $('.test').val().replace("inf", "∞");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
});
In this sample I am using an input. You can change that to div

How to identify if user is typing in RTL or LTR language?

I want imitate google's input,
It automatically change input's typing direction based on the language you're typing in.
How can I identify if user is typing in RTL or LTR language?
It must work cross-browser.
You should use the attribute dir="auto"
e.g.
<html dir="auto">
This way the browser will look at the first strongly typed character and adjust the text automatically.
For reference, here is the W3C documentation on this: http://www.w3.org/International/tutorials/new-bidi-xhtml/qa-html-dir
If you want to mimic Google's directionality recognition algorithm, you will need to listen to input change, recognize whether the character inserted was RTL or LTR (or neutral) and change the textbox's dir="" attribute accordingly.
Google's algorithm, for the most part, seems to calculate the majority of strong characters in the string and decide the directionality from that. If you type RTL it will switch the context to RTL, and if you then switch to LTR for the same paragraph, it may switch the context again to LTR if those characters outnumber the RTL ones.
For comparison, Facebook uses a direction algorithm as well, but it is slightly different - it seems to use the first strong character to decide the direction of the paragraph rather than the overall number.
(For the record, Google also seems to have several algorithms for this; Gmail behaves slightly differently than Google Hangouts which is different than how the input in Google search is aligning itself. In these things, there are mostly no "right" or "wrong" answers but rather what fits your use case)
Whichever method you choose to implement, you first need to identify what the user is typing. There are several ways to do this, but I would recommend the following:
Read a little about Unicode BiDirectional Algorithm (especially about "strong" type characters) http://unicode.org/reports/tr9/
Find a good way to identify strong characters in your context. An example of a regex to do that can be found in MediaWiki's Language file (where group 1 is LTR and group 2 is RTL): https://github.com/wikimedia/mediawiki/blob/6f19bac69546b8a5cc06f91a81e364bf905dee7f/languages/Language.php#L174
You can create a JavaScript method that listens to the user's input, uses the regex above to identify which strong character is used (either by first character or by counting them all, whichever works best for your use and scale) -- and change the textbox's dir="" attribute accordingly.
Make sure you later display the submitted text with the correct alignment later, so you may have to either use something to store the alignment you picked or to re-recognize whenever you render it. Either way, don't forget that the display needs the same dir="" attribute as well.
Too late but maybe it can help someone one day.
This function will add direction attribute to the input field based on the first inputed character, and when user clears input text the function will detect the new language of text again.
$.fn.set_input_direction = function()
{
$(this).off('keypress').on('keypress',function(e){
_this = $(this);
setTimeout(function()
{
if(_this.val().length > 1){
return;
} else {
var rtl_regex = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/;
var is_rtl = rtl_regex.test(String.fromCharCode(e.which));
var direction = is_rtl ? 'rtl' : 'ltr';
_this.css({'direction' : direction});
}
});
});
};
To use it:
$('input').set_input_direction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
function checkRTL(s) {
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');
return rtlDirCheck.test(s);
};
// BIND KEYPRESS
var input = $('input').on('keypress', keypress)[0];
function keypress(e) {
// need to wait for the character
setTimeout(function () {
var isRTL = checkRTL(String.fromCharCode(e.charCode)),
dir = isRTL ? 'RTL' : 'LTR';
input.style.direction = dir;
}, 0);
}
</script>
</head>
</body>
<h1>Auto Direction
<sup>(RTL | LTR)</sup>
</h1>
<input type="text" onkeypress="keypress()" placeholder="Type something…" />
</body>
</html>

Change HTML Textbox: Overwrite Instead of Insert as User Types

I am working on a service which will allow editing of text. To aid the user in the process, I'd like to allow the user to set a text field to overwrite mode, as is possible in Word, etc. How can the behaviour of an HTML text box be changed to overwrite instead of insert text as the user types?
For example, if the textbox had the text:
This is a trst.
The user could click between the r and the t, type a single e and the text would then be
This is a test.
with the cursor between the e and the s. I'm currently using jQuery, so methods using either that or pure javascript would be preferred. I would accept any reasonable solution, however.
That's a bit of crazy but it seems to work somehow :)
Based on this answer and this answer this piece of code was created.
$("textarea").on("keypress", function(e) {
var key = String.fromCharCode(e.which || e.charCode || e.keyCode);
if (/[A-Za-z0-9 ]/.test(key)) {
var text = this.innerHTML;
var caret = getCaret(this);
var output = text.substring(0, caret);
this.innerHTML = output + key + text.substring(caret + 1);
setCaretPosition(this, caret + 1);
return false;
}
return true;
});​
DEMO: http://jsfiddle.net/aHSzC/
It works but now I have no time to fix a small bug I found.
If you press Backspace it seems to behave like a forward eraser.
Anyway, here is the code that can be improved. Feel free to edit my answer and do whatever you like.
Input elements have an onkeypress attribute. You could make it call a function that gets rid of the character after the cursor. jQuery has a Caret extension that you could use to find out where the caret is.

ASP.NET Javascript Hide/Show Read More for Long Text

So at the moment I have a literal to which I assign a value to from database. I.e an Introduction to a programme.
What I am looking to do is i.e if the text is larger than 100 Characters, to only display the first 100 Characters and then display a javascript link "Read More" which when clicked displays the rest of the content.
Any Ideas ?
Use CSS elipses is one quick easy solution:
span.ellipsis {
text-overflow:ellipsis;
}
The other in .NET would be something like:
string YourText = "rgr";
if (YourText.Length > 100)
{
YourText = YourText.Substring(0, 100);
YourText += "... Read more";
}
There are a few issues with the above though, there are lots of refinements you can make but that should get you going.
Have two Literals or Labels, one of which is hidden with style="display: none" (Visible=False won't emit the HTML so you can't interact with it from Javascript) and contains the full text.
Your first label/literal ("Read more") needs to have an onclick event that does something like :
javascript:void(show(LongerText.ClientId));
show and hide are defined as:
function show(id) {
document.getElementById(id).style.display = "block";
}
Set the text of your labels to be a cut down (substring'd) version of the text and the full text.
Should be enough to get you started, but let me know if you need anything more :)
Just to make it extra clear, the structure of the document is this:
Title of document
Read more
hidden text

Categories

Resources