Question

I made the following jQuery code:

$(".button").live("click", function(){  // When you click on .button...
    $(this).before(" <div class='add'> +1 </div> ");  // ...a new div appears.
});

The new "+1" div is currently styled to appear in a predetermined position.

Can you help me pass the cursor coordinates to the div position, in order to make the div appear where the user clicks?

Était-ce utile?

La solution

Here you have an example:

http://jsfiddle.net/JPvya/1109/

Note: i would use allways the same div to have more clear the DOM. But, if you need a DIV for each click, change the code in order to create a new div each click. HTML

<html>
    <head></head>
    <body id="BodyID">
        <div id='test'>Test div is testing</div>
        <hr></hr>
    </body>
</html>

CSS

#test {
    width: 200px;
    height: 200px;
    border: 1px dotted blue;
}

jquery script

jQuery(document).ready(function(){
  $("#BodyID").click(function(e){
         $("#test").show(2000);
         $("#test").offset({left:e.pageX,top:e.pageY});

         })
})

Reference: Set Div position to Mouse position with jQuery

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top