0

I am getting CSS 'left' property value. now it is set on -50. so i want to get only 50 can this be done with split function or there is another way to do that. Also why split function is not working in my function

<head>

<script type="text/javascript" src="jquery-1.7.2.js"></script>

<script type="text/javascript">

$(document).ready(function() {

$('.box').click(function (){

    var kar=parseInt($(this).css('left'))

var jj= kar.split('')

alert(jj[0])

    })

});
</script>


<style>

.container {

    margin:auto;
    width:500px;
    position:relative

}


.box { background:#FF0000; width:200px; height:200px; position:absolute;left:-50px;}

</style>

</head>

<body>
<div class="container">
<div class="box"></div>

</div>
</body>

4 Answers 4

2

I think what you are looking for is the Math.abs function:

Math.abs(-50); // 50
Math.abs("-50"); // 50

The split function works on strings and returns an array with all parts of the string separated by the given delimiter. You are giving an empty string as delimiter, which splits your string after each character like this:

"-50".split(""); // result is: ["-","5","0"]
var kar = -50;
kar.split(""); // TypeError: kar.split is not a function

If you are getting a string back like "-50px", then you can do it like this:

var leftAsInt = parseInt("-50px".replace(/[A-Za-z]/g, ""),10);
console.log(Math.abs(leftAsInt)); // 50

Also: there is no jQuery involved in this (besides the .css() function), split and abs are functions of JavaScript's predefined core objects String and Math.

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

Comments

1

use Math.abs:

var kar = parseInt($(this).css('left')),
    jj = Math.abs(kar);

References:

Comments

1

how about trying this

alert(Math.abs(kar))

hope this helps

Comments

0

Yes, you can use split function

try below code..

var jj= kar.split('-')

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.