Julian Paolo Dayag
Julian Paolo Dayag

Reputation: 3719

JQuery adding number value

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...

Upvotes: 0

Views: 997

Answers (4)

Dan
Dan

Reputation: 1033

The following works for me:

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

Upvotes: 0

Lukx
Lukx

Reputation: 1283

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)

Upvotes: 3

Fabrício Matté
Fabrício Matté

Reputation: 70149

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

Upvotes: 3

zessx
zessx

Reputation: 68790

Isn't it ?

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

Upvotes: 0

Related Questions