Flashing background color appears as I scroll

Whenever a user touchstarts on a div, I want to apply a background-color to that specific div. Then, as the user scrolls, I use the $(window).scroll event to either reset or remove the background-color from all divs.


However, my issue arises when a user both touches and scrolls on the divs, causing the background-color to flash in and out. I want to prevent the div's background-color from changing during a (tap, touch + scroll) event. If this is unclear, you can refer to apps like Facebook Messenger or Snapchat for a visual example.

Flashing divs: https://i.sstatic.net/OWtN5.gif

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>

Answer №1

One way to handle changing the background color in a more efficient manner is by tracking the pointer position during a touchstart event and then comparing it to the position during a touchend event. If the positions are the same, indicating no scrolling, you can change the background color of the div and set a timeout to reset it. However, if the positions differ, indicating scrolling, there is no need to change the background color.

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", "");
}

Answer №2

give this a shot

$(window).scroll(function() {
resetBackground();
});

 //----------------------------------------------

$(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() {
  resetBackground();
 });

function resetBackground() {
  $(".❄").css("background-color", "");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a Custom CSS Theme in JavaFX

Hey everyone, I stumbled upon this amazing JavaFX theme called Flatter on . I've been attempting to implement it for a couple of hours now, but I'm struggling with the process. Can someone provide me with a detailed guide on how to activate thi ...

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

JQuery Scroll Spy Implementation

I have structured the page with a header at the top and 3 columns below. The left column contains a menu, the middle column is a text container, and the right column is another section. As the page scrolls up, the menu becomes fixed in position which func ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Issue with Javascript array not returning expected array output

CSS: <input type="text" onblur="checkInputValue(this.value);" placeholder="Enter Value" id="input_value" name="data[input][input_value]"> JavaScript: function checkInputValue(v){ var validValues=[2, 4, 8, 16, 32, 64, 128]; var fi ...

What's the best way to send keystrokes to a dynamically generated input field within a parent div element when it is clicked on?

I need help with this issue: our website features a dynamic table that loads data (students' grades) into a div element. When the div is clicked, a new child element input is added to the div, allowing us to input a new grade using the SendKeys method ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

Clicking on two links simultaneously to avoid them being blocked as pop-ups

Is there a way to open 2 URLs at the same time with just a click? I'm open to using jquery, javascript or any other method. Priority is on efficiency and speed, but I am open to all options. I attempted using onclick in the anchor tag and also tried ...

CSS: Placing a Column below a Float Positioned Column

While performing some maintenance on a website, I noticed that one page is not displaying correctly. There is a container div for a column on the left and a container div for content on the right, both within an overall page content container. Below these, ...

Is it possible for the jquery in index.html to retrieve variables stored in the connected controller?

Utilizing jQuery for a dropdown navigation that dynamically adjusts its CSS properties based on the user's login status within the application. The visibility of links in the navigation is determined by the boolean value of the loginStatus variable se ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Dynamic JavaScript Calculations Based on User Input in Real Time

I am in the process of creating a dynamic calculator that updates in real-time based on user input from a form. I have successfully implemented this feature using a sample div, but I am encountering difficulties when attempting to display the total inside ...

jQuery menu animation not triggering until second click

I am currently working on implementing a menu that will slide in after clicking the hamburger button (located in the upper right corner). Instead of simply appearing, I wanted to use a jQuery function for a smoother sliding effect. However, I seem to be e ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

What is the reason behind receiving the error "PHP Warning: Trying to access property "nodeType" on null" when using this PHP AJAX search function?

I am working on developing a real-time search feature inspired by an example from w3schools, which can be found at this link: https://www.w3schools.com/php/php_ajax_livesearch.asp. My task involves searching through an xml file containing 1000 different it ...

The Javascript and CSS code for a button fails to trigger the animation function after the initial click

Is it possible to trigger the animation function multiple times after the initial click without making changes to the HTML code? The ID and class in the code must remain as they are. I attempted to use the display property set to none, but it did not yie ...

What is the best approach to utilizing BeautifulSoup to locate all the links on a page containing the string "/pl/oferta/"?

Currently, I am delving into Python with a focus on web scraping. Specifically, I am utilizing BeautifulSoup to extract only the links from: while searching for the string "/pl/oferta/'". import logging import requests from bs4 import BeautifulSoup ...

The background size cover feature is not functioning properly on mobile devices, especially on longer pages

In my Next.js project, I am encountering an issue with the background image not displaying on longer pages when viewed on a Google Pixel 3a device. Here is how it looks on shorter pages that do not exceed the viewport height: https://i.sstatic.net/jJBTy.pn ...