0
votes

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?

2
Te problem is your z-Index in your CSS! .. Set z-Index for class .cuad higher than .card.Daniel

2 Answers

2
votes

Why dont you use hover

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

});
0
votes

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);
         });
})