Search code examples
javascriptimagemap

JavaScript imagemap code doesn't work


What is wrong with this code? Why is my imagemap not working?

function createimg()
 {
         var img = new Image();
       img.src='link/to/image';
       img.alt='Next image';  img.id = 'span1'; img.style.zIndex = 10;
       img.style.position = 'absolute';  
       img.style.display='block'; 
       img.style.top = '130px';
       img.style.padding='10px'; 
       img.style.left='440px'; 
       img.usemap='#testmap';  
       img.className ='dynamicSpan';
       document.body.appendChild(img);

        var mymap = document.createElement('map');
        mymap.name = 'testmap';
        document.body.appendChild(mymap);

        var areatag = document.createElement('area');
        areatag.shape = 'rect';
        areatag.coords = '900,200,1100,1000' ;
        areatag.href =   'http://www.google.com';
        mymap.appendChild(areatag);
        document.body.appendChild(areatag);

        return img;
   }

UPDATE:

I reconstructed my code like this, but it is still not functional:

 function createimg()
 {
         var img = new Image();
       img.src='link/to/image';
       img.alt='Next image';
       img.id = 'span1';
       img.style.zIndex = 10;
       img.style.position = 'absolute';
       img.style.display='block';
       img.style.top = '130px';
       img.style.padding='10px';
       img.style.left='440px';
       img.usemap='#testmap';
       img.className ='dynamicSpan';


        var mymap = document.createElement('map');
        mymap.name = 'testmap';
        mymap.id = 'testmap';


        var areatag = document.createElement('area');
        areatag.shape = 'rect';
        areatag.coords = '0,0,500,500' ;
        areatag.href =   'http://www.google.com';
        areatag.target = '_blank';


        //append area to map
        mymap.appendChild(areatag);
        // append map to document
        document.body.appendChild(mymap);
        //append image to document
        document.body.appendChild(img);

        return img;
   }

Solution

  • here's the solution:

    you should use

    img.setAttribute("usemap", '#testmap')

    instead of:

    img.usemap = "#testmap"