user7768059
user7768059

Reputation:

Finding Position Of Character In String, JS

Description: When I say finding position of character in a string I mean finding how many pixels from the left and top sides of the screen the character is.

Would I have to surround the character in a span tag and find where that span tag is located? Or is there a better way to do this with pure JS?

Upvotes: 3

Views: 1307

Answers (1)

Sam
Sam

Reputation: 1479

Span you propose is best solution I guess. If you dont want to manage values of character width and so on. It depends on font-family and which letter is contained.

A great way could be implement a function to dynamicaly generate hidden DOM div one time per character you want to evade. It calculates width of each one and add to a variable. It will be the offset value. You understand?

I think that implementing it is worth it with your professionalism and adapted to your scenario since we have not example of it :) I give you something as a pseudo-code of what I mean if it helps:

function calculate_offset () {
var offset;
var position = element.positionX;
   for i in 0 to string.indexYouWant 
       do 
          variable = get_string[i]_value;
          generate_div(variable);
          offset += calculate_div_width();
   end for  

return position+offset;
}

Upvotes: 1

Related Questions