0

HTML code:

<body>
    <img class="card" src="card.jpg"/>
</body>

CSS code

.card{position: static; margin-top: 100px; margin-left: 100px; z-index: 10; }

.cuad{ opacity: 0.3; border: 4px solid black; width: 40px; height: 40px; z-index: 5; }

jQuery code:

$(document).ready(function(e){
$(".card").mouseenter(function(e){
    $("body").append($("<div class='cuad'></div>").css({"position": "absolute", "top": (e.pageY-24)+"px", "left": (e.pageX-24)+"px"}));
});
$(".card").mouseleave(function(e){
    $(".cuad").remove();
});

});

The problem with this code is that the div, which is created at the entrance to the area of element with the class .card, flashes, because automatically call the function mouseleave, in the end it goes into an infinite loop.

Does anyone see a bug in the code?

Ihor Patychenko
  • 196
  • 6
  • 19

2 Answers2

2

Why dont you use hover

$(document).ready(function(e){
    $(".card").hover(function(){
         //Add code for mouse enter
    },
    function(){
         // Add code for mouse leave
    });

});
writeToBhuwan
  • 3,233
  • 11
  • 39
  • 67
0

There are more problems to this. Your element is recreated every time. Change the z-Index of .card and .cuav. Make .cuav higher that card and then

Try this:

$(document).ready(function(e) {
    var el = $("<div/>", {
                 class : 'cuad'
                });

$(".card").hover(function(e) {
                 $("body").append(el);
                 $(el).css({
                    position : "absolute",
                    top : e.pageY - 24,
                    left : e.pageX - 24

                 });

               }, function() {
                $(".cuad").remove(el);
         });
})
Daniel
  • 4,816
  • 3
  • 27
  • 31