I've been playing with jQuery-UI Draggable https://www.jcmatheson.com/page/blog.html and was wondering if there was a way of changing the gif to a different background image if you drag and shook it hard enough with the mouse? Basically, you drag the sleeping head around and if shook, changes to a waking expression jpg.
Sorry if this is quite vague, I'm very new to jQuery and this is my first question on SO.
Thanks!
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#draggable" ).draggable();
});
</script>
#draggable { width: 256px; height: 256px; padding: 0.5em; }
.ui-widget-content {
border: none;
background: #ffffff url(https://piskel-imgstore-b.appspot.com/img/5505e3cf-b2a5-11e7-a7d6-77854951e175.gif) 50% 50% repeat-x!important;
color: #222222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="draggable" class="ui-widget-content">
<p></p>
</div>
You could use a setInterval() function and mesure the amount of pixels moved in that time. If moved more than 25px 3 times in a row, that could mean it's been shaken
$(".shakeMe").draggable({
});
var lastLeft;
var shakeCount = 0;
var lastShake = 'right';
setInterval(function(){
left = $(".shakeMe").offset().left;
// var dist = Math.abs(lastLeft - left);
var dist = lastLeft - left;
if(dist > 25 && lastShake == 'right') {
shakeCount++;
lastShake == 'right';
if(shakeCount >= 3) {
$(".shakeMe").css("background", "red");
}
} else {
if(dist < -25 && lastShake == 'left') {
shakeCount++;
lastShake == 'left';
if(shakeCount >= 3) {
$(".shakeMe").css("background", "red");
}
}
shakeCount = 0;
}
console.info(shakeCount);
lastLeft = left;
}, 200);
This is running every 200ms (one fifth of a second) but this could be reduced.
Also, you have to move it 25px 3 times in a row, so it depends what you what a "shake" to actually be