I need to loop all of the eight gradient directions by clicking on a target, like this:
Instead of background, you can get the style attribute.
$(this).attr('style')
It will return "background: linear-gradient(to top,red,yellow)"
.
Then you use .slice(28)
to cut out "background: linear-gradient("
and .split(',')[0]
to get the direction.
let a = $(this).attr('style').slice(28).split(',')[0];
You can access the linear-gradient
value with background-image
.
$('.targ').on('click', function() {
let direction = $(this).css('background-image').split(',')[0].slice(16);
const gradientColors = $(this).css('background-image').split(',').slice(1);
if (direction == 'to top') {
direction = 'to top right'
} else if (direction == 'to top right') {
direction = 'to right'
} else if (direction == 'to right') {
direction = 'to right bottom'
}
$(this).css('background', 'linear-gradient(' + direction + ',' + gradientColors.join(','));
});
.targ {
width: 54px;
height: 54px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='targ' style='background: linear-gradient(to right,red,yellow)'></div>
Don't over complicate it, make it simple:
var c=0;
document.querySelector('.targ').addEventListener('click',function(e) {
e.target.style.setProperty('--d',(c+=90)+"deg");
})
.targ {
width: 54px;
height: 54px;
cursor: pointer;
background: linear-gradient(var(--d,0deg),red,yellow)
}
<div class='targ' style=''></div>