mohsin
mohsin

Reputation: 540

How to Fetch Coordinate Value (x,y) from jQuery Code and Store in NSString?

div tag is used for performing bold, italic, etc. operations in UIWebview. I want to fetch the position coordinates when the user touches the div tag through JavaScript/jQuery.

I found the code in JSFiddle.

$(document).ready(function(e) {
    $('#C').click(function(e) {
        var posX = $(this).position().left, posY = $(this).position().top;
        var x =  e.pageX - posX;
        var y =  e.pageY - posY;
        alert( (x) + ' , ' + (y));
    });
});
#C { 
    width: 100px;
    height: 100px;
    cursor: pointer;
    background: #2f2f2f;
    position: absolute;
    top: 50px;
    color: #fff;
    font: bold 15px Arial; 
}
<div id="C" style="left:500px;">
    position() <br /> 
    mouse <br/> 
    position 
</div>

How to store x and y coordinates from jQuery to NSString using string by evaluating JavaScript from string?

Upvotes: 0

Views: 86

Answers (1)

Sabrina
Sabrina

Reputation: 617

As per the UIWebView Class Reference, you need to use stringByEvaluatingJavaScriptFromString and return a value from your Javascript function.

This question on Stack Overflow has a few answers that go into pretty good detail. I suggest starting there.

Update in response to comment:

jQuery is simply a Javascript library. The fundamentals still apply. To return a value in jQuery (in this case, altering the function you've provided) you just need to... well... return the value.

var getCoord = function() {
    var posX = $(this).position().left, posY = $(this).position().top;
    var x =  e.pageX - posX;
    var y =  e.pageY - posY;
    return (x) + ' , ' + (y); // this is the line that returns your coordinates
};

getCoord(); // to call your function

Upvotes: 1

Related Questions