When user enters correct text, an image rollovers/changes - javascript

I am designing a language learning site. I want to have it when someone enters text into the text box it starts to roll over certain images. Take a look at my sample below
http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
So, when the user enters "na" the first symbol highlights as you see in my sample. When he enters "ma" the second symbol should highlight/rollover. I want all the symbols to stay rolled over while the correct text is entered. so if the user types "nama" the first two symbols should be rolled over to show they got it correct and once the last correct text is entered all three will be rolled over.
Can this by done? I will accept advanced and simple methods.

$(document).ready(function() {
var text = ['na', 'ma', 'ba'];
$("#elemID").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed.indexOf(item)!=-1) {
$('li', 'ul').eq(index).find('img').addClass('correct');
}else{
$('li', 'ul').eq(index).find('img').removeClass('correct');
}
});
});
});
FIDDLE
EDIT:
At the top of your page, in the <head> section, add:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Then wrap the code in document.ready, see the edited code above on how to do that ?

On change of the input box, you could do something like this: (totally untested)
var parts = ["na", "ma", "blah"];
var start = 0;
for (var i = 0; i < parts.length; i++) {
var currentPart = parts[i];
var $img = $(".images img:nth-child(" + i + ")");
var end = start + currentPart.length;
if (str.length >= end && str.slice(start, start + currentPart.length) == currentPart) {
$img.addClass("highlight");
} else {
$img.removeClass("highlight");
}
start += currentPart.length;
}

Related

JS complex operation of the selected text

Great minds JavaScript, please help.
I need to deal with the complex operation of the selected text.
I have some text with a lot of html tags, and I need to get a function that returns the following result:
The user selects text in a particular tag with the class, for example <div class="text">,
and the function is activated in the event that:
$('.text').mouseup(function (e){...});
returns the beginning of the selection
returns the end of the
selection identifies a particular tag, with his class
Moreover:
the number of characters to be given html tags,
but you can exclude
some tags example ,
Ok, some code, what I have:
$(function () {
$('.text').mouseup(function (e){
$(this).highlight(getSelectionText());
})
})
this demo
Here we highlight the desired part of the text, but did not return the
correct position
In addition, the text is released coincidentally
characters, and I need it for the position
You might want to try this:
$(function () {
$('#detailBoxParagraph').mouseup(function (e){
var selectedText = getSelectionText();
$(this).removeHighlight();
$(this).highlight(selectedText);
var txt = $(this).text();
var pos = [];
var i = txt.indexOf(selectedText);
if(i > -1) {
pos.push({"start": i+1, "end": i + selectedText.length});
}
while (i != -1) {
i = txt.indexOf(selectedText, i + 1);
if(i > -1) {
pos.push({"start": i+1, "end": i + selectedText.length});
}
}
console.log(pos);
})
//alertSelection();
})

javascript not changing the text color

I have a function that I want to change the font color of the user entered string if it is equal to a certain word located in an array.. So far when I step through it it says that it changes the font color but it actually never updates it to the screen and I don't know why. Here is what I have so far
function getLastWord() {
var input = document.getElementById("my_text");
//var input = document.getElementById(textArea.value);
//var lineIn = document.getElementById(my_text).innerHTML;
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
if (input == null) {
input == " ";
}
//lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if (reservedKeyWords[i] === lastWordTyped) {
lastWordTyped = lastWordTyped.fontcolor("blue");
my_text.replace(inputValue, lastWordTyped);
} else {
}
}
}
}
I see two issues with the code thus far.
You are using 'fontcolor("blue")' parameter on the lastWordTyped. The proper syntax to change color is element.style.color="#CCC".
You will need to wrap the last typed word in a span so you can target it and apply the color to just that word.
string.fontcolor is legacy, and should not be used even though I could see it as a viable option in this case
Essentially, what you are doing is adding font tags around the word:
var txt = 'hello world';
txt = txt.fontcolor('blue');
//txt = '<font color="blue">hello world</font>';
You do not show what you do with the result, but if you actually put it in an HTML element it should work, even though instead of using fontcolor, I'd rather use element.style.color. This would require slightly more work though:
var ele = document.querySelector('#my_text');
ele.style.color = 'blue';
ele.innerHTML = lastWordTyped;
If you still want to go with the .fontcolor method, you could just keep what you have in the question and add
input.innerHTML = my_text;

change text color only of user entered string in AJAX extended textbox

I am extending a texbox control with AJAX Autocomplete and I have successfully implemeted an autocomplete text box where once the user enters 3 characters my database returns a list of records that begin with the first 3 characters entered by the user.
I then changed this feature to use some Fuzzy logic so that the strings that returned contain no less than the 3 characters entered by the user and progressively becomes a shorter more refined list as the user enters a more specific search string.
I then used the inlcluded CSS class of the Autocomplete control to change the backgorund color and selected item color in the extended texbox.
<asp:AutoCompleteExtender
ID="TextBox1_AutoCompleteExtender"
runat="server"
DelimiterCharacters=""
Enabled="True"
EnableCaching="True"
ServiceMethod="GetCompletionList"
ServicePath="~/search/strngSrch.asmx"
TargetControlID="TextBox1"
UseContextKey="True"
CompletionSetCount="30"
CompletionInterval="10"
MinimumPrefixLength="2"
CompletionListItemCssClass="itemHighlighted"
CompletionListHighlightedItemCssClass="itemHighlighted1">
</asp:AutoCompleteExtender>
What I would like to do now is change the color of the text ONLY in each string (list item) that matches what the user is entering after 3 or more characters have been entered.
I have been searching for something like this on the web for 2 days and have not found a similar solution. My efforts have become more than frustrating.
User Enters: fish
Results list should look like:
Fishing (The 4 letters = to Fish should be red in each of these list items)
New Fishing licenses
Renew Fishing License
Fish and hatchery lists
If anyone has any links or similar type of solution I would be very pleased to look it over.
This functionality could best be compared to searching for a text string in a PDF where the word background is highlighted yellow for each occurance within the doc. I don't care if it turns the background a different color ONLY behind the text the user entered, or changes the text color.
thanks,
I would like to thank the link below for providing a solution to the question. I finally found something that almost worked. In the interest of not posting only a link, please review the working code below.
Note some of my minor changes in the below code over the original found in the link at the end.
<script type="text/javascript">
function aceSelected(sender, e) {
var value = e._item.innerText; // get_text();
if (!value) {
if (e._item.parentElement && e._item.parentElement.tagName == "LI")
value = e._item.parentElement.attributes["_innerText"].value;
else if (e._item.parentElement && e._item.parentElement.parentElement.tagName == "LI")
value = e._item.parentElement.parentElement.attributes["_innerText"].value;
else if (e._item.parentNode && e._item.parentNode.tagName == "LI")
value = e._item.parentNode._value;
else if (e._item.parentNode && e._item.parentNode.parentNode.tagName == "LI")
value = e._item.parentNode.parentNode._innerText;
else value = "";
}
var searchText = $get('<%=TextBox1.ClientID %>').value;
searchText = searchText.replace('null', '');
sender.get_element().value = value;
}
function acePopulated(sender, e) {
//Give BehaviourId here
var behavior = $find('AutoCompleteEx');
var target = behavior.get_completionList();
if (behavior._currentPrefix != null) {
var prefix = behavior._currentPrefix.toLowerCase();
var i;
for (i = 0; i < target.childNodes.length; i++) {
var sValue = target.childNodes[i].innerHTML.toLowerCase();
if (sValue.indexOf(prefix) != -1) {
var fstr = target.childNodes[i].innerHTML.substring(0, sValue.indexOf(prefix));
var pstr = target.childNodes[i].innerHTML.substring(fstr.length, fstr.length + prefix.length);
var estr = target.childNodes[i].innerHTML.substring(fstr.length + prefix.length, target.childNodes[i].innerHTML.length);
target.childNodes[i].innerHTML = "<div class='autocomplete-item'>" + fstr + '<B><font color=red>' + pstr + '</font></B>' + estr + "</div>";
}
}
}
}
On your AutoComplete Extender provide the following values....
BehaviorID="AutoCompleteEx"
OnClientPopulated="acePopulated"
OnClientItemSelected="aceSelected"
That is about it, I had to perform some minor changes and debugging. Like the closing java script tag is wrong, and the function to get the value from the textbox did not work with e.get_value() so I changed it to e._item.innerText and seem to be working just fine.
Source of Solution

display alert when mouse hovers over word in text

I have been struggling with this for a few days. I need somebody to steer me in the right direction. I have been searching on the web. I am not sure if I took the right approach. What I need is that each time a person hovers over a particular keyword, it should display an alert box. In this example the word is else. When I run the code it does not give any errors and does not display anything when mouse hovers on the word.
function on_func2()
{
var searchString = 'else';
var elements = document.getElementById('paragraph2');
for (var i = 0; i < elements.length; i++)
{
if (elements[i].innerHTML.indexOf(searchString) !== -1)
{
alert('Match');
break;
}
}
}
I would do something like this:
It will go through and find all else words, and wrap them in a span with a listener bound:
<p id="hello">What else would you say?</p>
-
​var hello = document.getElementById('hello');
var str = hello.innerHTML;
str = str.replace(​​​ /\b(else)\b/g, '<span onmouseover="func1()">$1</span>' );​​​​​​​​​​​​​​​​​​​
hello.innerHTML = str;
function func1() {
alert('there');
}
Check out the fiddle.
Using jQuery lettering plugin
<p class="word_split">if you were not there, else I would not have won.<p>
$(".word_split").lettering('words');
$('.word_split').mouseover(function(event) {
var word=event.target.innerHTML;
if (word == "else")
alert("Yep");
});
here's a demo: jsFiddle

Correctly entered text changes image?

I am trying to achieve an effect where the correctly entered text will result in the image changing, letting the user know he typed it in correctly. The only problem I am having is if the person types the first two characters correctly, even if the third is incorrect it still stays changed.
Example: Take the word "ate" for instance.
If the user types in " aate " with two A's the image still remains highlighted/changed.
Is it possible to make it somehow stay exact to what the correct text needs to be ?
JSFIDDLE here with google images for example:
http://jsfiddle.net/japaneselanguagefriend/wjx6b/
p.s. I hope I explained things cleary! I have been up and at this for hours and I could use a helping hand. Thanks so much guys!
What you need is to check on the index
$("#test").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed[index] == text[index]) {
$('li', 'ul').eq(index).find('img').attr('src', happy[index]);
}else{
$('li', 'ul').eq(index).find('img').attr('src', grumpy[index]);
}
});
});
http://jsfiddle.net/wjx6b/2/
Or exact match would need to compare the the current text with the array letters combined
$("#test").on('keyup', function() {
var typed = this.value;
var theWord = ''
for(i=0;i<typed.length;i++){
theWord += text[i];
}
$.each(text, function(index, item) {
if (typed[index] == text[index] && typed == theWord) {
$('li', 'ul').eq(index).find('img').attr('src', happy[index]);
}else{
$('li', 'ul').eq(index).find('img').attr('src', grumpy[index]);
}
});
});
http://jsfiddle.net/wjx6b/4/
​

Categories