How to detect mouse click position in jquery

2.3k views Asked by At

I am trying to make a website where user can post there article. I want them allow some html tagging. But as user may not know about html, I am using some button for automatic inserting the content, so that they can add some effect to their content. For example if any user wants to write some bold text he can click on a button named "bold" and code will be automatically inserted. Following is an image of what is my design.

enter image description here

Everything is working fine. I am adding all those code at the end. But it is not good while editing. Let user wants to add some bold text at the middle. So he expects to click at the middle and press the bold button, but even in the case I add my code at the end.

So is there any way to detect the mouse click position and adding my text right after that ? Any suggestion(I am using jQuery)?

2

There are 2 answers

3
Captain John On

In your mouse click event you can use the clientX and clientY variables to find mouse click points. It can be done as follows:

$("#myButton").click(function(e) {
    alert(e.clientX + ", "+ e.clientY);
})

Hope that helps

0
Zac On

If you are not using textarea, and I assume you already put the area (example: content_node) as :

content_node.designMode="on";
content_node.contentEditable= true;

Then, you just need use [document.execCommand], such as:

document.execCommand("FontSize","false",sSize|iSize);
document.execCommand("Bold","false",null);

Further reading: https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand