I’m displaying a story on a website, I would like to dynamically add an image within the story, how could I do that?
I don’t want to add it at the beginning of the story or at the end of the story, but dynamically embed it somewhere in the middle of the story with either a float left or right.
I’m using PHP and jQuery and the story could have HTML in it as well. If I have a story like so, how can I embed the image?
Nullam nibh lorem, aliquam sed sodales
sed, egestas at tortor. Curabitur
commodo urna non elit scelerisque ac
rutrum tellus interdum. Phasellus arcu
leo, congue eu ultrices vitae,
pulvinar vitae neque. Sed tempor dolor
eu eros aliquet in egestas metus
bibendum. Etiam eleifend tellus vitae
purus consectetur eget venenatis
ligula cursus. In hac habitasse platea
dictumst. Nulla in elit erat.
Vestibulum mattis malesuada sapien
quis sodales. Sed id tortor id odio
mollis iaculis eu a sem. Morbi
pellentesque lorem vitae ante molestie
<img src="pathtoimage" style="float:left;">sit amet pulvinar
lorem porta. Mauris tempor laoreet
quam vel tristique. Donec ultrices
porttitor sapien, eu consectetur
tortor rhoncus eget. Nulla vehicula
magna nisi. Aenean consectetur
placerat laoreet. Praesent blandit
quam turpis, non egestas elit. Quisque
dolor turpis, sollicitudin id
elementum sit amet, sodales at metus.
Duis tortor neque, scelerisque a
adipiscing quis, blandit non velit.
Donec mattis, nibh at pharetra porta,
erat massa tempor quam, at hendrerit
sem nibh sit amet magna. Sed auctor
lectus ac magna accumsan commodo. Nam
vehicula velit et neque eleifend sit
amet eleifend leo euismod.
Since the story can contain, HTML, the problem can get very messy. The following algorithm will insert an image an arbitrary percentage into the story, and make sure it’s not inside an HTML tag. Note that it sacrifices efficiency for straightforwardness.
Warning: This code can still insert the image tag somewhere it doesn’t belong, depending on what HTML the story allows. For example, if inline
scripttags are allowed1, the algorithm could have “fun” effects. 😉See the live demo at: jsbin.com/agimi5/3.
Suppose, the story is all inside
<div id="StoryGoesHere">. Then insert the image with, say:Given:
The algorithm can be easily converted to PHP, if you prefer to do the manipulation server-side.
1 If inline
scripttags are allowed, you’ve got much bigger problems, anyway.