Reputation: 4137
box-shadow has a syntax like this
box-shadow: h-shadow v-shadow blur spread color inset;
I would like to set up a jQuery function that increments the h-shadow, v-shadow, and blur by 2px everytime a button click takes place. What would it look like?
$('button[type=submit]').bind('click': function(){
$('div').css('box-shadow'???, '+=2');
})
Upvotes: 1
Views: 885
Reputation: 1452
You could do that by using a couple of regular expressions to get the color, hshadow, vshadow, blur, spread and whether it is inset or not. Once you ve got that, you can simply increment it by 2. Put it all together and apply to the button.
Here's the updated jsfiddle (with the color and inset values obtained from the original box-shadow CSS. This is how it would look (updated):
var pattern = /\d+px/g; //will match only those values with a number + px
var colorPattern = /rgb\(.+\)/; //regex to get the color
var incr = 2;
$('#btn').bind('click', function(){
var currentBoxShadowCSS = $(this).css('box-shadow');
var color = currentBoxShadowCSS.match(colorPattern)[0];
/*
That will get us the color:
rgb(255, 0, 0)
*/
var matchesArr = $(this).css('box-shadow').match(pattern);
/*
That will return ["0px", "0px", "5px", "0px"]
That s basically [h-shadow, v-shadow, blur, spread]
We are concerned with only the first 3
*/
var oldHShadow = matchesArr[0].split('px')[0];
var newHShadow = parseInt(oldHShadow, 10) + incr;
var oldVShadow = matchesArr[1].split('px')[0];
var newVShadow = parseInt(oldVShadow, 10) + incr;
var oldBlur = matchesArr[2].split('px')[0];
var newBlur = parseInt(oldBlur, 10) + incr;
//check if this was an inset shadow
var inset = currentBoxShadowCSS.indexOf('inset') > -1 ? ' inset': '';
//we got what we need, apply it
$(this).css('box-shadow', newHShadow + 'px ' + newVShadow + 'px ' + newBlur + 'px ' + color + inset);
});
Upvotes: 2
Reputation: 12886
You can try:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<style type="text/css">
#test{ box-shadow: 2px 2px 2px; width: 100px; height: 100px;}
button{ height: 20px; width: 100px}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$("#test").css('box-shadow', incValues($("#test").css('box-shadow')));
});
});
function incValues(values){
var splits = values.split('px');
splits[0] = splits[0].split(' ');
splits[0] = splits[0][splits[0].length-1];
return (parseInt(splits[0])+2) +'px ' + (parseInt(splits[1])+2) +'px ' + (parseInt(splits[2])+2) +'px ';
}
</script>
</head>
<body>
<div id='test'></div>
<br/>
<button>Test</button>
</body>
</html>
Upvotes: 3