1

I have a web page and for internal links I want to emphasis where the visitor jump after clicking on an internal link on current page. It is just like SO's comment or answer notification. First the target's background will be orange then it will smoothly turn back to white.

I could have done this but color change is not smooth.

HTML part

<a href="#section1">go to section 1</a>

<a href="http://google.com">Google</a>

<a name="section1"><a><h3 id="section1">Section 1</h3>

jQuery part

$(function () {
    $("a[href^='#']").click(
    function () {
        var $id = $(this).attr("href");
        $($id).css({"background-color":"#cc7733", "transition":"background-color"});

        setTimeout(function () {
            $($id).css("background-color", "#ffffff");
        }, 2500);

    });

});

JS Fiddle is here

zkanoca
  • 9,664
  • 9
  • 50
  • 94

3 Answers3

8

Transition should have duration and easing.

{"transition":"background-color 0.5s ease"}

NOTE: 0.5s is sample time, change this to your own.

DEMO

qtgye
  • 3,580
  • 2
  • 15
  • 30
3

The problem is that you're specifying "transition":"background-color" and aren't specifying a time scale. You need to change this to include a time:

..."transition":"background-color 0.2s"

A better way to do it, however, would be to set the transition property on the CSS itself, then use jQuery to give the element a new class:

/* Select any element with a href attribute. */
:link { /* You could use [href], but :link has better browser support */
    transition: 2.5s; /* Transition takes 2.5 seconds. */
}

.changedBackground {
    background: #fff;
}
$($id).addClass('changedBackground');

This way you keep the styling separate from the JavaScript, allowing you to easily change the style by only modifying the CSS.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

You can use .animate() like this

$($id).stop()
      .css({"background-color":"#cc7733"},1000)
      .animate({"background-color":"#FFF"},1000);

Note: You need to include jQuery UI to your project for animate to work.

DEMO

Anton
  • 32,245
  • 5
  • 44
  • 54
  • 2
    This only works if jQuery UI is used, and including jQuery UI just to animate a background seems a bit overkill. – James Donnelly Aug 26 '14 at 08:46
  • @JamesDonnelly Ah yeah i forgot to note that in the answer. And yeah it's a bit overkill but OP might want to know how it's done even though there are better answers. – Anton Aug 26 '14 at 08:49