Miura-shi
Miura-shi

Reputation: 4519

When user enters correct text, an image rollovers/changes

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.

Upvotes: 0

Views: 148

Answers (2)

adeneo
adeneo

Reputation: 318302

$(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 ?

Upvotes: 1

Michael Baldry
Michael Baldry

Reputation: 2028

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;
}

Upvotes: 1

Related Questions