Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?

I want to write a function where, when I click anywhere on a string (or sentence) in HTML, it will tell me if that is a letter or a whitespace. Is this even possible? For example, I click on anywhere inside this sentence:

<div id='sentence'>The cat in the hat.</div>

Say I click on the letter "a" inside "cat". I want it to return an alert telling me that I clicked on a character. Say I click on the whitespace between "cat" and "in". I want it to return an alert saying that I clicked on a whitespace.

It may sound impossible but one idea I have is that maybe you click somewhere and check to the left and right of where you clicked (for example, you clicked right between a whitespace and a letter), and if at least one of characters is a whitespace (say to the left), it should return that you clicked on a whitespace... would this be easier to implement? I just need some advice on this.

like image 225
James Nine Avatar asked Nov 28 '25 21:11

James Nine


2 Answers

Working example @ http://jsfiddle.net/Kai/k4YMS/

function clickify (e) {
    var arr = e.innerText.split("") || e.textContent.split(""),
        max = arr.length,
        i = 0,
        template = "<span onclick='alert(this.innerText || this.textContent);'>$c</span>",
        result = "";

    for (; i < max; i += 1) {
        result += template.replace("$c", arr[i]);
    }

    e.innerHTML = result;   
}
like image 190
Kai Avatar answered Dec 01 '25 12:12

Kai


Not directly possible, but if you take every single character in html elements this can be possible. Here is what i thought:

var $sentence = $("#sentence");
var sentence = $sentence.html();

//we'll use this after we recreate the sentence
function tellMeWhatIAm(){
  //as its name says it tells what it is
  alert($(this).text());
}

$.each(sentence,function(i,t){
  //clear the sentence
  if(i==0) $sentence.html("");
  //create every char again
  //and bind click event to our function above
  var $span = $("<span/>",{"text" : t, "click" : tellMeWhatIAm});
  //append the chars back to the sentence wrapper
  $sentence.append($span);
});

Haven't tested it though, but the idea is pretty straightforward.

Hope it helps, Sinan.

like image 43
Sinan Avatar answered Dec 01 '25 11:12

Sinan