Reputation: 157
I'm trying to add a long shadow by adding css styling with jQuery for any elemet has data-shadow attributes. the shadow color will be the value of the elemet. So this is my try:
<div data-shadow="#A00909">Test</div>
div{
background:red;
display:inner-block;
font-size:44px;
text-align:center;
font-weight:bold;
color:#fff;
padding:40px;
overflow:hidden;
width:50%;
margin:auto;
}
// jQuery
$(function() {
$( "*" ).attr( "data-shadow", function( i, value ) {
var t = $(this).data('shadow');
var n, sh = "",long = 90;
for( n = 1 ; n <= long ; n++ ){
sh = sh + n + "px "+n+"px "+ value;
if( n != long ) sh = sh +", ";
}
$(this).css("text-shadow",sh);
});
});
in the jQuery code I'm trying to get the value of data-shadow
but without success.
Otherwise, when I use a specified value like in the following code - it works:
$( "*" ).attr( "data-shadow", function( i, value ) {
var temp = "#A00909";
var t = $(this).data('shadow');
var n, sh = "",long = 90;
for( n = 1 ; n <= long ; n++ ){
sh = sh + n + "px "+n+"px "+ temp;
if( n != long ) sh = sh +", ";
}
$(this).css("text-shadow",sh);
});
});
How to use the value of data-shadow
instead of temp value for each element has data-shadow
attributes?
Upvotes: 2
Views: 144
Reputation: 206024
You can go for the $("[data-shadow]")
selector (as suggested by Jack) and access directly the element's .css()
callback (cause $()
) is already a collection of elements:
$('[data-shadow]').css("text-shadow", function() {
var t=$(this).data().shadow, sh="", long=90;
for(var n=1; n<=long; n++) sh += n+"px "+n+"px "+t+(n<long?" ,":"");
return sh;
});
Upvotes: 0
Reputation: 9388
You were close! First, instead of doing a query selector of all *
, you can use an attribute selector
.
After that, you'll just call each
as you were doing (rather than attr
).
Here's an updated fiddle: http://jsfiddle.net/jpattishalljr/b0fpkccf/4/
$(function() {
$('[data-shadow]').each(function(i, value) {
var t = $(this).data('shadow');
var n, sh = "",long = 90;
for( n = 1 ; n <= long ; n++ ){
sh = sh + n + "px "+n+"px "+ t;
if( n != long ) sh = sh +", ";
}
$(this).css("text-shadow",sh);
});
});
Upvotes: 3