Mohsin Kureshi
Mohsin Kureshi

Reputation: 33

JavaScript Magnifying glass

I built a magnifying glass in JavaScript, which works well when I click on it or click and dragging it, but it should not hide from the screen.

$(".menu-left-preview-box-preview").bind('click', function (e) {
    window.location = "page" + ($(this).index() + 1) + ".html";
});

var native_width = 0;
var native_height = 0;
var magnifyIsMouseDown = false;
$(".magnify").parent().mousedown(function (e) {
    magnifyIsMouseDown = true;
});
$(".magnify").mousemove(function (e) {
    if (magnifyIsMouseDown) {
        if (!native_width && !native_height) {
            var image_object = new Image();
            image_object.src = $(".small").attr("src");
            native_width = image_object.width;
            native_height = image_object.height;

        } else {
            var magnify_offset = $(this).offset();
            var mx = e.pageX - magnify_offset.left;
            var my = e.pageY - magnify_offset.top;

            if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
                $(".large").fadeIn(100);

            } else {
                $(".large").fadeOut(100);
            }
            if ($(".large").is(":visible")) {
                var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
                var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
                var bgp = rx + "px " + ry + "px";

                var px = mx - $(".large").width() / 2;
                var py = my - $(".large").height() / 2;
                $(".large").css({ left: px, top: py, backgroundPosition: bgp });
            }
        }
     }
});

$(".magnify").parent().mouseup(function (e) {
    magnifyIsMouseDown = false;
    $(".large").fadeOut(100);
});
$(".magnify").parent().mouseleave(function (e) {
    $(".large").fadeOut(100);
});

manageSlide();

By default the magnifying glass must be there on the screen. The magnifying glass can be dragged and after it's dropped it must remain there at it's dropped position.

On clicking and dragging the magnify glass is working well, but it should not hide from the screen. It should be there on screen.

Provide handle of magnify glass with that circle (in design).

Working example: http://jsfiddle.net/mohsin80/4ww8efx5/

Upvotes: 1

Views: 1502

Answers (1)

pedromendessk
pedromendessk

Reputation: 3646

I replaced the if (magnifyIsMouseDown) { by if (isDragging) { and created the following methods:

var isDragging = false;
$(".magnify").parent().mouseup(function(e) {
    isDragging = false;
});
$(".magnify").parent().mousedown(function(e) {
    isDragging = true;
});

To make a simulated drag event with jQuery.

Here is the fiddle. Hope it helped :)

Upvotes: 1

Related Questions