Search code examples
javascripthtmltarget

Is there a unique ID for objects clicked within target?


With the following code, as you can see with each oval created, the name always remains the same. So no matter which oval I click, I get the same name. Is there some kind of unique ID buried in the target attribute?

<!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
} 

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv';// + i;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>

Solution

  • Try this

    <!DOCTYPE html>
    <html lang="en">
    <input type="button" onClick="doit()" value="Do it">
    
    <script>
        var id = 1;
    function doit() {
        drawOval(160,80,50);
        myOval = document.getElementById("newdiv");
    } 
    
    function drawOval(width, height, radius) {
        if (document.createElement) {
    
           newdiv=document.createElement("div");
           newdiv.style.width = width+"px";
           newdiv.style.height = height+"px";
           newdiv.style.backgroundColor = 'red';
           newdiv.style.visibility = 'visible';
           newdiv.style.borderRadius = radius+"%"
    
           newdiv.id = 'newdiv' + id;// + i;
            id++;
           document.body.appendChild(newdiv);
        }
    }
    
    document.onclick = function(f){
        alert(f.target.id)
    }
    </script>
    
    </html>