What is the best way to apply a background color to an element temporarily?

Check out the following code snippet:

$('html,body').animate({scrollTop: -20 + $('.clsname').offset().top});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

... (additional script lines)

In addition to that, I need to incorporate this code as well:

var $el = $(".clsname"),
      x = 2000,
      originalColor = $el.css("background");

  $el.css("background", "orange");
  setTimeout(function(){
    $el.css("background", originalColor);
  }, x);

I am trying to achieve both scrolling to an element and setting its background color to orange for a duration of 2 seconds. How can I accomplish this?

Please note: Ideally, I would like the orange color to smoothly fade away after 2 seconds.

Answer №1

You have the ability to utilize JavaScript in order to modify it based on different times of day, such as morning, day, and night.

$(document).ready(function(){
    var currentDate = new Date();
    var currentTime = currentDate.getHours();
    if (currentTime > 19 || currentTime < 6)
      // When it is past 7PM or before 6AM, switch to the night theme for the ‘body’ element
      document.body.className = "night";
    else if (currentTime > 16 && currentTime < 19)
      // If the time falls between 4PM and 7PM, apply the sunset theme to the ‘body’ element
      document.body.className = "sunset";
    else
      // Otherwise, use the default ‘day’ theme
      document.body.className = "day";
});

Answer №2

this code snippet will alter the background-color once the user scrolls past a certain point on the page.

 $('html,body').animate({scrollTop: -20 + $('.clsname').offset().top}, 2000);

setTimeout(function(){
   $('.clsname').css({backgroundColor: 'orange'});
}, 2000);
setTimeout(function(){
   $('.clsname').css({backgroundColor: 'transparent'});
}, 3000);
.clsname{
  transition: all 2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №3

To change the background-color, you can utilize css animation.

$('html,body').animate({
  scrollTop: -20 + $('.clsname').offset().top
});
.clsname {
  background: none;
}
.clsname {
  -webkit-animation-name: example;
  /* Safari 4.0 - 8.0 */
  -webkit-animation-duration: 2s;
  /* Safari 4.0 - 8.0 */
  animation-name: example;
  animation-duration: 2s;
}
/* Safari 4.0 - 8.0 */

@-webkit-keyframes example {
  from {
    background: orange;
  }
  to {
    background:none;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br...
  <div class="clsname">scroll to top</div>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

Answer №4

Utilize a promise by passing it a function that will execute upon the completion of animation. Another option is to use the success callback, but using a promise is preferable because it prevents the issue of double callbacks caused by <html> and <body> (included for browser compatibility).

$('html,body').animate({scrollTop: -20 + $('.clsname').offset().top  }).promise().done(function(){
    var $el = $(".clsname"),
    x = 2000,
    originalColor = $el.css("background");
    $el.css("background", "orange");

    setTimeout(function(){
        $el.css("background", originalColor);
    }, x);
});

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

Creating a dynamic HTML table by dynamically populating a column

I have limited experience with javascript, and I am working on a personal project that I enjoy. In the table below, you will find various location names along with their distances from the initial location. This serves as a travel companion for me to refe ...

Learn the steps to access a Collection in Meteor.js and then send it to a function once the DOM has finished

Is there a way to ensure that a query on the collection is executed before running another function when a specific div has been rendered? When attempting the following, an error from .highcharts() is returned indicating that the div #chart cannot be foun ...

Removing a post in Meteor-React using a submission modal is not possible as the post is not defined

After creating an additional submit modal for user confirmation when deleting a post from the collection, I'm facing difficulty in targeting the post. I also have a productivity query - should I include the DeletePost component in each post component ...

Having difficulties sending data from axios to my node server, resulting in an empty object being returned

Here is the client-side code I am using: <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport&quo ...

What is the best way to maintain a fixed header for a content div?

I recently developed a website using angularjs. <html> <head></head> <body ng-app="app1" ng-controller = "ctrl1"> <header></header> <div ng-view></div> <footer></footer> </body> </ht ...

Tips for increasing the width of a button within an HTML table heading

I'm attempting to make a button within a table <th> expand to the full width and height of the header column, even if a table cell in the same column is larger than the text. If I set the width to 100% in CSS, the button ends up matching the siz ...

The function get_the_category() is not compatible when used within the <figcaption> element

I'm encountering a strange issue. I'm attempting to incorporate a javascript gallery from this site into my WordPress theme. My goal is to show the post category as a figcaption, but when I insert my PHP code inside, it doesn't function prop ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

Bootstrap's landing page problem

I am currently working on creating a landing page using bootstrap and have encountered an issue with the text alignment in my section containing icons and tags. In order to make the text appear clean and concise, I want the text to be displayed in either o ...

Disable postback onkeypress event in the page

I am encountering an issue with my ASP.NET 4.0 form where I have multiple textboxes within divs that are dynamically shown or hidden. Specifically, I have a textbox with an onkeypress event defined as follows: <fieldset> <div class="WizardSte ...

How to successfully send additional data along with a file upload in an AJAX request using CodeIgniter

I am currently facing an issue where I am successfully uploading a file in a php codeigniter project using ajax. However, I also need to post some additional values to the database along with the file upload. I am unsure of how to achieve this. Can anyone ...

I would like to check if a given username and password exist in my JSON data

Trying different methods but not achieving the desired outcome. I have limited knowledge about JSON, gathered some information from online sources. var loginDataList = [{ "username": "abc", "password": "abc123" }, { "username": "richa", "p ...

Customize the appearance of a <label> tag when it is inside an <input> tag that is marked as invalid

In an ideal scenario, I wish for the text on a label to change color when the input value is considered invalid. For instance: <form> <label> Enter your name: <input type="text"> </label> </form> Ideall ...

What is the best way to enable a link upon clicking while simultaneously disabling the others using JavaScript?

When I click on a link, I want to handle just that one element. However, when I click on another link, the active class is not being removed from the previous ones. Can anyone offer assistance with this issue? Here's my code: let parentT = document.qu ...

Use JavaScript to submit a form in Django containing the <a></a> tag

I am having an issue with my form submission using JavaScript. When I try to submit the form, it is sending a GET request to the backend, but I am expecting it to send a POST request instead. Here is the HTML file code snippet: <form id="my_form&qu ...

Issue with formik onchange event not filling data in Material UI TEXTFIELD component

Greetings! I am currently working on a React project where I am managing the authentication process. I am using Material UI and Formik for validation and handling input changes. However, I encountered an issue with my onchange Formik handler in the TEXTF ...

Unfortunately, Node Sass does not have compatibility with your current environment, which is Windows 64-bit with an unsupported runtime

Having been a regular user of Node.js to utilize gulp and sass for my HTML projects, I recently encountered a new issue. An error message stating "Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (57)" has no ...

An error has occurred: String cannot have property 'innerText' created

I'm encountering an issue while attempting to dynamically add posts to my post div. The problem arises when I try to include image URLs in the process. Switching from innerText to innerHTML did not resolve the issue, and the array I added is also not ...

Retrieve information from an HTML form, make updates to the database, and exhibit the data in a table on the current page with the help

I'm in need of some assistance. I have a small application that utilizes a Java Servlet and an HTML form. The user enters data into the HTML form, and upon clicking the submit button, the Java servlet retrieves this data in its post method and stores ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...