I’m new to Javascript and would like to modify a text string by clicking on individual characters. The string is: 0000 0000 0000 0000 representing a binary number. I would like to be able to toggle a 0 to a 1 by clicking directly on the text.
I have tried to use onclick() but have only managed to detect a click for the entire paragraph. What would be an appropriate method to detect which character is clicked?
For such a small number of characters, the easiest way is to put each of them in its own span:
I’d also put all of those in a container, and hook the
clickevent on the container rather than on the individual spans, so:Then hook it up:
In your click handler, use
event.targetto find out which span was clicked:More to explore:
As you can see above, I had to work around the fact that some browsers use the standard
addEventListener, and others (IE8 and earlier) useattachEvent. I recommend using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over those kinds of browser inconsistencies for you, and add a lot of very useful utility functionality so you can focus just on what you’re trying to do.For example, that handler code written using jQuery: