0

can someone help me debug this please??? i'm really don't know whats wrong with my code...

i'm trying to add number value to another number value.... but it does not work as i expected...instead it just add the number as a string.

Here is my demo: (already solved)

and here is the js code:

$(document).ready(function(){
$("#map").click(function(e){
    var x = parseInt((e.pageX - this.offsetLeft)) - parseInt("140");
    var y = parseInt((e.pageY - this.offsetTop)) - parseInt("140");


  var coor = $("#map").css("background-position").split(" ");
  var cx = parseInt(coor[0].replace("px",""));
  var cy = parseInt(coor[1].replace("px",""));


    $("#map").stop().animate({"backgroundPosition": x+cx+" "+y+cy},"slow");
     alert("X:"+x+", CX: "+cx+"\n Y:"+y+", CY:"+cy+"\n Background-pos:"+$("#map").css("background-position"));

});
});

please tell me what's wrong with it...

4 Answers 4

3

Put parentheses () around your arithmetic operations.

$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");

Otherwise, adding the whitespace string will force the JS to concatenate your numbers as a string.

Fiddle example

Sign up to request clarification or add additional context in comments.

Comments

3

In your animate-Statement towards the end you set background position to:

x+cx+" "+y+cy

This is interpreted as a string, because the four +-operations are interpreted equally. You do, really, concatinate a string (" "). Thus, the entire result of this expression becomes a string and the addition is no longer an addition but a concat.

However, if you capsulate the math into parenthesis, then you should be fine. Your second-last line becomes:

$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");

(note the extra brackets around x+cx)

2 Comments

You replied a little after me, but that was because of your overly explanatory answer. Well, I was expecting someone to explain it a little more in-depth and I like that, +1 =]
Hahah thanks ;-) I saw your reply popping in while I was still typing, and I am glad that both of our answers helped in their own way!
0

Isn't it ?

var x = parseInt((e.pageX - $(this).offset().left)) - parseInt("140");
var y = parseInt((e.pageY - $(this).offset().top)) - parseInt("140");

Comments

0

The following works for me:

$("#map").click(function(e){
        alert(e.pageX);
        alert(this.offsetLeft);
        alert(parseInt(e.pageX)-parseInt(this.offsetLeft));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.