Search code examples
javascriptjquerymouseeventmouseoveronmouseover

Dynamic mouseenter


I appended a few divs with inside img tags. Every tag has own unique id = "theImg"+i where "i" is number. I want to mouseover on specific img and show the content of span (which also have specific id with number). Here is my code so far but not working.

var j;  
document.onmouseover = function(r) {
    console.log(r.target.id);
    j = r.target.id;
}

$(document).on({
    mouseover: function(e){
     $("span").show();
    },
    mouseleave: function(e){
     $("span").hide();
    }
}, "img#"+j);

Solution

  • If you have a span after every img, maybe it's a good idea to not use JavaScript at all? ;-)

    You could use :hover pseudoclass in CSS, making your thing always work reliably.

    Consider the following example:

    img + span {
      display: none;
    }
    img:hover + span {
      display: block;
    }
    
    /*/ Optional styles /*/
    div {
      position: relative;
      float: left;
    }
    div img + span {
      position: absolute;
      color: #fff;
      background: #27ae60;
      border: solid 1px #2ecc71;
      border-radius: 50px;
      z-index: 1;
      bottom: 1em;
      width: 80%;
      left: 50%;
      margin-left: -43%;
      padding: 2% 3%;
      text-align: center;
    }
    <div>
      <img src="https://placehold.it/400x200">
      <span>This is an image of a gray rectangle!</span>
    </div>
    
    <div>
      <img src="https://placehold.it/200x200">
      <span>This is an image of a gray square!</span>
    </div>
    
    <div>
      <img src="https://placekitten.com/g/400/200">
      <span>This is an image of a cute kitten inside a rectangle!</span>
    </div>
    
    <div>
      <img src="https://placekitten.com/g/200/200">
      <span>This is an image of even cuter kitten inside a square!</span>
    </div>