Javascript trying to get the id of the image that the mouse is moving

I want to get the id of the image that hovers over. But I don't understand how to get the ID. Can anyone help me :). TY!

function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {

var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);

}
};

      

Using the placeImage function, I will place the images. Now I want to add a mouse event and change the class of the target image.

<div id="thumbnails" onmouseover="mouseOver(this);" ></div>

      

I added a mouse pointer to all the thumbnails. But I cannot get the id of the image the mouse is hovering with. I want to call the id or change the image.className of this image. But I don't know what to call it. Now it only warns "thumbnial"

function mouseOver(e){
 alert(e.id);
}

      

+3


source to share


3 answers


Use the keyword this

:

<div id="thumbnails" onmouseover="mouseOver(this);" ></div>

function mouseOver(e){
   alert(e.id);
}

      

Edit comment :



var image=document.createElement("img");
   image.className += " Atributes";
   image.src="images/foto_klein_"+i+".jpg";
   image.width="135";
   image.height="90";
   image.alt="foto_klein_"+i;
   image.id="image"+i;
   image.mouseover = mouseOver;
   image.position="relative";
   div.appendChild(image);
   image.style.marginRight = '10px';
   _img.push(image);

}

      

Pay attention to the function mouseOver

called when you hover the image. this

will refer to an image element, not a div.

+7


source


To get id

images when you hover over it, try this:



function placeImage(x){
    var div = document.getElementById("thumbnails");
    div.innerHTML = ""; // clear images
    for (var i =0; i <= x; i++) {
        var image=document.createElement("img");
        image.className += " Atributes";
        image.src="images/foto_klein_"+i+".jpg";
        image.width="135";
        image.height="90";
        image.alt="foto_klein_"+i;
        image.id="image"+i;
        image.position="relative";
        image.onmouseover = mouseOver;    // <-- Added this
        div.appendChild(image);
        image.style.marginRight = '10px';
        _img.push(image);
    }
}

function mouseOver(e) {
    alert(this.id);
}

      

+1


source


Hope this helps, although I'm not sure about it while working on a dynamically added image.

document.ready = function () {
    var thumbnails = document.getElementById("thumbnails");

    var imgs = thumbnails.getElementsByTagName("img");

    for( var i=0; i<imgs.length; i++ ) {
        imgs[i].onmouseover = function() {
            alert( this.id );
        }
    }
};

      

-1


source







All Articles