Reputation: 7971
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>
Upvotes: 0
Views: 884
Reputation: 8052
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
.
Upvotes: 2
Reputation: 588
Yes, you can use split function
try below code..
var jj= kar.split('-')
Upvotes: 0
Reputation: 1239
how about trying this
alert(Math.abs(kar))
hope this helps
Upvotes: 1
Reputation: 253308
use Math.abs:
var kar = parseInt($(this).css('left')),
jj = Math.abs(kar);
References:
Upvotes: 1