How to highlight a div in a few seconds using jQuery

I want to add the following to the page:

When I click on the div, I want:

  • change the background color of the pressed button on the div for a few seconds.
  • will return to the original background color after a few seconds.

I want to do this using only available jQuery functions, i.e. without using a plugin or anything else. I'm relatively new to jQuery, but I think a possible solution involves using the class change of the selected div and using a timer.

I'm not sure how to put it all together. Can someone provide some lines that show how to do this?

This is what I still have:

$(function(){ $('div.highlightable').click(function(){ //change background color via CSS class $(this).addClass('highlighted); //set a timer to remove the highlighted class after N seconds .... how? }); }); 
+8
jquery
source share
5 answers

One way is as follows: setTimeout :

 $(function () { $('div.highlightable').click(function () { $(this).addClass('highlighted'); setTimeout(function () { $('div.highlightable').removeClass('highlighted'); }, 2000); }); }); 
+21
source share

You can use jQuery UI Highlight Effect :

 $(".myDiv").effect("highlight", {}, 3000); 

Demo in stack fragments:

 $(function() { $(".myDiv").click(function() { $(this).effect("highlight", {}, 3000); }); }); 
 .myDiv { margin: 0px; width: 100px; height: 80px; background: #666; border: 1px solid black; position: relative; } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> <div class="myDiv"></div> 
+8
source share

I think you're looking for the Highlight effect.

http://docs.jquery.com/UI/Effects/Highlight

+6
source share

You can use the setTimeout function:

 $('div.highlightable').click(function(){ var $this = $(this); //change background color via CSS class $this.addClass('highlighted'); // set a timeout that will revert back class after 5 seconds: window.setTimeout(function() { $this.removeClass('highlighted'); }, 5 * 1000); }); 
+4
source share

For posterity, there is an answer here that includes the jQuery queue () function.

 $('.menul').addClass('red').delay(1000).queue(function(next){ $(this).removeClass('red'); next(); }); 

From: https://forum.jquery.com/topic/inserting-a-delay-between-adding-and-removing-a-class#14737000002257187

0
source share

All Articles