Use of split function using jquery - javascript

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>

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.

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

how about trying this
alert(Math.abs(kar))
hope this helps

Yes, you can use split function
try below code..
var jj= kar.split('-')

Related

Select and Replace an embedded style with jQuery

Is it possible to select and replace an embedded styles background path with jQuery? I'm having trouble getting this to work.
<script>
$(document).ready(function($) {
function myReplaceFunc() {
var $str = $('style');
$str.replace('wcsstore', 'mytest');
}
myReplaceFunc();
});
</script>
<style>
#test{
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
</style>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>
Any help much appreciated.
Aside from the issue with calling replace() on a jQuery object, your approach to this is flawed. While it's possible to amend the content of <style> tags with JS, it's very far from the best solution.
Instead, you should set the background-image on the element directly using the css() method. You can provide a function to this method which receives the current value as an argument. You can then call replace() on that - as you currently are - to update the value. Try this:
$(document).ready(function($) {
function myReplaceFunc() {
$('#test').css('background-image', function(i, bg) {
return bg.replace('wcsstore', 'mytest');
});
}
myReplaceFunc();
});
#test {
background: url("/wcsstore/***/en_GB/images/suppliershop/ecomheader.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="test">Test 1</section>
<section id="test2">Test 2</section>
Use .text() chained to jQuery() to get, set the .textContent of the element
$str.text($str.text().replace('wcsstore', 'mytest'));
1- get the background image url from css applied
var bg = $('#test').css('background-image');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
2- change the url
var new_url = bg.replace('wcsstore','mytest');
3- replace the url
$('#test').css('background-image', 'url(' + new_url + ')');

Check if field contains numbers, wrap the numbers with container and class?

If you have something simple like this in HTML:
<div class="main">Item 7,000</div>
How to make javascript apply an html element and a class for the 7,000 part (because its numeric) on page load? To something like this:
<div class="main">Item <span class="wrap">7,000</span></div>
Or maybe just an html element, if with class not possible.
I apologies I don't have any code to share right now. I'm still browsing other questions.
Maybe it should be something with jQuery if $.isNumeric() is true then apply element?
There will be edge case but accomplishes your goal
$(function () {
$(".main").each(function (index, element) {
var $element = $(element);
var wrapped = $element.text().replace(/(.+?)((\d{1,3},?)+)/g, '$1<span class="wrap">$2</span>');
$element.html(wrapped);
});
});
.wrap {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">Item 7,000</div>
<div class="main">Item 960</div>
<div class="main">Item 7,000,000</div>
If you use node.textContent you can get the string inside the div
string = document.querySelector('#main').textContent // --> "Item 7,000"
From here you can use Array#split to separate each word:
array = string.split(' '); --> ['Item','7,000']
Now remove the comma and check isNaN for each, return an array w:
newNode = array.map((e)=> isNaN(e.replace(/,/g,"")) ? e : {element:'span', content: e})
Now you have ['Item', { element: 'span', content: '7,000'}] which you can use to generate the contents of the div element in your example...
There might be way better ways to do this, I am just trying to help :)
Use javascript regex find a matching number and replace with span
var regex =/\b(\d+)\b/g
var regex =/\b(\d+)\b/g
var text = document.getElementById("main").innerHTML;
document.getElementById("main").innerHTML = text.replace(regex,'<span class="wrap">$1</span>')
span.wrap{
color:red;
}
<p id="main">Item : 7000</p>

Insert all divs with same class into an array?

I want to insert all divs which have the class .page into an array, then call each using the array iteration. For example the array pages[] should allow me to add certain effect to the div in pages[2].
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
//apply your effects using pageDivs[i]
}
Do you want to do like this ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr=[];
$(".page").each(function(){ arr.push($(this));});
$.each(arr,function(key,val){ val.css('color','gray')});
});
</script>
</head>
<body>
<b>.page content will be colored in gray.</b><br/><br/>
<div class="dontDo">The quick </div>
<div class="page">brown fox jumps</div>
<div class="doIt"> over the lazy dog</div>
<div class="page"> over the lazy dog</div>
</body>
</html>
I think in some of browsers getElementByClassName is not supported.However you can use calssName property like this :
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
//insert this elm into array
array.push(obj);
}
}
.getElementsByClassName is not supported < IE8. If you aren't worried about that, then Sunil's response will work for you.
If you want the jQuery way:
$(".page").each(function(index) {
// do stuff here
});
Happy iterating.

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

Count divs with a certain class

Seems pretty simple but I can't get it to work.
I have two divs with the class 'user'. I want to output "you have 2 divs".
<script type="text/javascript">
$(document).ready(function() {
function divcount() {
var mycount = $('.user').length();
document.write(mycount)
}
});
</script>
I'm sure I'm missing something simple..
It’s either $('.user').length (length property of Array) or $('.user').size() (size method of jQuery).
Length is a property not a function. Size is a function.
$(".user").length // use the length property
$(".user").size() // use the size method
notice that the code must be include in the $(function(){...}) block; like:
$(function(){
alert( $(".user").length );
alert( $(".user").size() );
});
It's just $('.user').length. It's a property, not a method call.

Categories