Alon Shmiel
Alon Shmiel

Reputation: 7121

Add img to td after td clicked

I have a table with one row, with one cell, that has a text. the text is in the center of the td.

while clicking the td, I want to add an image after the text. I don't want that the text will be moved, but will be stay in the same place.

this is my jsfiddle:

http://jsfiddle.net/alonshmiel/L7qn3/1/

in this jsfiddle, the text moves left.

<table>
    <tr>
        <td style="border:1px solid red; width:100px; text-align:center;" onclick="func(this);">
            sfh
        </td>
    </tr>
</table>

thank you all!

Upvotes: 0

Views: 48

Answers (2)

James Craig
James Craig

Reputation: 6854

The only way to do this is by giving the text a fixed margin instead of centring it. That way the text will stay centred when new content is added.

<td style="border:1px solid red; width:100px;" onclick="func(this);">
    <span style="margin-left:38px;">sfh</span>
</td>

Here's the example JSFiddle

Upvotes: 2

Goran.it
Goran.it

Reputation: 6299

You need to place script tag before the table, otherwise browser can't find the function since function is declared afterwards.. Here is working example FIDDLE

<script>
    function func(elem) {
    elem.innerHTML += "<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5Ojf/2wBDAQoKCg0MDRoPDxo3JR8lNzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzf/wAARCAAQABADASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQMEBf/EACQQAAEDBAEDBQAAAAAAAAAAAAECAwQFERIhABQiQRNCUWGR/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAfEQEAAgEEAwEAAAAAAAAAAAABAxECACExQRITMlH/2gAMAwEAAhEDEQA/AN5ymSaWUmTSXZkhBbV0rSgSpJJuTYK0Mdj75fVYMZ9TcRlKDLDTq0qjxgEOY37dW3dCvBvccEOXGrMNmFPkNR32UlZmvLClObPZux93z44qfVKUoejFjP8ARpxcS0X8SlwZbF8tEKH5xskGUkmOZnSdUVXfe69fmoGM5HF6iOxfpcvJbsONjHhTZs5Nf//Z'>"
}
</script>
<table>
    <tr>
        <td style="border:1px solid red; width:100px; text-align:center;" onclick="func(this);">
            sfh
        </td>
    </tr>
</table>

Upvotes: 2

Related Questions