Archive for August, 2013

Using JavaScript to create and change images

I know, I know – how many times have you been asked to create JavaScript code to dynamically change one Smurf icon contained inside a hyperlink to another icon. For me, it’s an almost weekly occurrence. But what if you need to do the whole thing in JavaScript. As in, the image can’t exist before you add your code. And, the image is actually part of a link? Before you start rolling around on the ground sobbing “It can’t be done!”, here is how you do that there thang (yes, I said thang):

    <script type=”text/javascript”>

        function addLink() {

            var l = document.createElement(‘a’);

            l.setAttribute(‘id’, ‘smurf’);

            l.setAttribute(‘href’, ‘#’);

            var i = document.createElement(‘img’);

            i.setAttribute(‘id’, ‘smurfImage’);

            i.setAttribute(‘src’, ‘SmurfetteIcon.jpg’);

            i.setAttribute(‘onclick’, ‘document.getElementById(“smurfImage”).src = “PapaSmurfIcon.png”;’);

            l.appendChild(i);

            document.getElementById(‘main’).appendChild(l);

        }

I hope you have Smurf icons, because I’m not making any for you.

The code first create a link element to hold the precious image. Then I create an image element and populate its initial image, along with an onclick event that will switch the icon to a different Smurf. I then append the image to the link, and the link to the DOM.

And where else would you put this code except the body’s onload event?

<body onload=”addLink()”>

</body>

There, fantastic code that you can use in all your production environments.

Leave a comment