tags:

views:

84

answers:

4

I want to be add the following to a a page:

When a div is clicked, I want to:

  1. change the background color of the clicked on div for a few seconds
  2. revert back to the original background color after a few seconds

I want to do this by using only jQuery available functions - i.e. not using a plugin or anything else. I am relatively new to jQuery, but I think a possible solution involves the use of changing the class of the selected div and using a timer.

I am not sure how to put it all together though. Can anyone provide a few lines that show how to do it?

This is what I have so far:

$(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?
 });
});
+3  A: 

One way is to go about like this using setTimeout:

$(function(){
 $('div.highlightable').click(function(){
    $(this).addClass('highlighted');
    setTimeout(function(){
      $('div.highlightable').removeClass('highlighted');}, 2000);
});
Sarfraz
Exactly what I was looking for !
morpheous
+2  A: 

You could 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);
});
Darin Dimitrov
+1  A: 

I think you are looking for the Highlight effect.

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

Manaf Abu.Rous
A: 
<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"&gt;&lt;/script&gt;
  <style type="text/css">
  div { margin: 0px; width: 100px; height: 80px; background: #666; border: 1px solid black; position: relative; }
</style>

  <script>
  $(document).ready(function() {

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});

  });
  </script>
</head>
<body style="font-size:62.5%;">
  <div></div>
</body>
</html>
Space Cracker