Reputation: 641
My code is to apply div background-color
when user touchstart on each div. that's clear for you.
Then when user scrolling, I use $(window).scroll
.. event to reset or remove background-color for all div's.
But my problem is: when user (touch + scrolling) at div's, background-color is flashing out color! I want to: don't change div background-color when (tap, touch + scrolling).
if you don't understand my question, you can see: (facebook messenger friend conversations, snapchat conversations, stories ..etc)
Flashing div's:
My code: https://www.w3schools.com/code/tryit.asp?filename=GLUIAUU64MDX - RUN ON TOUCH DEVICES.
$(window).scroll(function() {
resetBg();
});
$(".❄").on('touchstart', function() {
$(this).css("background-color", "#7bffea");
});
$(".❄").on('touchend mouseleave mouseup blur click', function() {
resetBg();
});
function resetBg() {
$(".❄").css("background-color", "");
}
div.❄ {
display: block;
height: 150px;
border: 1px solid black;
margin: 10px 0px;
padding: 0px;
border-radius: 8px;
background-color: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
Upvotes: 2
Views: 339
Reputation: 31
try this
$(window).scroll(function() {
resetBg();
});
//----------------------------------------------
$(document).on('touchstart', '.❄', function(evt) {
var that = this;
var oldScrollTop = $(window).scrollTop();
window.setTimeout(function() {
var newScrollTop = $(window).scrollTop();
if (Math.abs(oldScrollTop - newScrollTop) < 3) $(that).css("background-color", "#7bffea");
}, 200);
});
$(".❄").on('touchend touchmove mouseleave mouseup blur click', function() {
resetBg();
});
function resetBg() {
$(".❄").css("background-color", "");
}
Upvotes: 1
Reputation: 876
Instead of setting background on touchstart
, you can get the pointer position at touchstart
and on touchend
check if pointer position is changed or not. If not, change the div background and set a timeout function to reset it. If the position of pointer is changed then it's a scroll so you don't need to change the background
let initialY = null;
$(".❄").on('touchstart', function(e) {
initialY = e.clientY;
});
$(".❄").on('touchend', function(e) {
if(e.clientY===initialY){
$(this).css("background-color", "#7bffea");
setTimeout(()=>{ //This is optional
resetBg();
},100);
}
});
function resetBg() {
$(".❄").css("background-color", "");
}
Upvotes: 1