Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to highlight a div for a few seconds using jQuery

Tags:

jquery

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?
 });
});
like image 352
morpheous Avatar asked Jul 25 '10 09:07

morpheous


People also ask

How do you make a Div highlighted?

To make it a 'clickable' area, you're going to want to put a <a></a> tag inside the div, and you may want to use jQuery to set the href attribute.

How do you highlight a div in HTML?

To Highlight text in HTML you have to use an inline element such as the <span> element and apply a specific background style on it. This will create the highlighting effect, which you can tweak in many different ways to create different looks.


1 Answers

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);
    });
});
like image 140
Sarfraz Avatar answered Oct 05 '22 06:10

Sarfraz