Search code examples
javascriptjqueryonmouseover

Make button clickable only if cursor inside div


I have a div generated via JS with a button in it which I want to make clickable only with a mouse, no manual link following should be possible.

Q1: Is there a way to make the button clickable only if the mouse cursor is inside the div?

<div class='modal-body' style='padding-top: 10px'>
<a href='?hash="+hash+"' class='btn btn-success btn-xs cbut "+hash+"'><span class='glyphicon glyphicon-forward "+hash+"'></span></a>
</div>

To prevent automated scripts from following the link such as iMacros, I have added the "hash" variable to the link name and class which is now random. Even so they can follow the link by adding a * wildcard in the macro script. So I'm outta ideas here.

Q2: Is there a definitive way to restrict link following to mouse only?


Solution

  • So here's how I made it work for me:

    1) Wrap the button inside an invisible element

    2) Remove the link and add it via the onclick event

    3) Disable the button by default

    <span style="position:relative;">
    <input type="button" onclick="document.location.href='?hash'" class="btn btn-success btn-xs" value="❯❯">
    <div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; cursor: default; display: none;" id="catch"></div>
    </span>
    

    4) Remove the invisible element which also triggers the re-enabling of the disabled button from within the target div:

    $("#catch").mouseover(function (evt) {
        $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
    });
    

    This way the button can no longer be targeted or activated unless the mouse cursor is placed over it. I've already beaten current iMacro scripts so this will do for now.

    LE: Spoke too soon, seems iMacros was able to target the button quite easily. However I also came up with a quick fix by adding a simple timeout for my function:

    $("#catch").mouseover(function (evt) {
        var $this = $(this)
        setTimeout(function () {
        $this.hide().prev("input[disabled]").prop("disabled", false).focus();
        }, 1000);
    });
    

    Thank you for all the inputs here which really kept me going.