104

I would like to implement something similar to 37Signals's Yellow Fade effect.

I am using Jquery 1.3.2

The code

(function($) {
   $.fn.yellowFade = function() {
    return (this.css({backgroundColor: "#ffffcc"}).animate(
            {
                backgroundColor: "#ffffff"
            }, 1500));
   }
 })(jQuery);

and the next call show yellow fade the DOM elment with box id.

$("#box").yellowFade();

But it only makes it yellow. No white background after 15000 milliseconds.

Any idea why it is not working?

Solution

You can use:

$("#box").effect("highlight", {}, 1500);

But you would need to include:

effects.core.js
effects.highlight.js

Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
  • Highlight source is here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.effect-highlight.js – styfle Feb 08 '13 at 00:39

15 Answers15

101

This function is part of jQuery effects.core.js :

$("#box").effect("highlight", {}, 1500);

As Steerpike pointed out in the comments, effects.core.js and effects.highlight.js need to be included in order to use this.

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
Baldu
  • 5,714
  • 2
  • 30
  • 19
  • 1
    I saw the demo in the jquery site http://docs.jquery.com/UI/Effects/Highlight#overview I have tried in my code but does not do anything. Do I need to download any extra. It says dependencies: Effects Core. It is this another plugin. – Sergio del Amo May 11 '09 at 16:19
  • Correct answer, but I'll just mention it's a built in function to the jQuery effects.core.js, not to the core jQuery file as animate(). Just thought it was worth clarifying. – Steerpike May 11 '09 at 16:21
  • 5
    Heh, as Sergio has so obviously just discovered... yes Sergio, you need to include the effects.core.js file and effects.highlight.js (check the source here: http://docs.jquery.com/UI/Effects/Highlight) – Steerpike May 11 '09 at 16:23
  • @R.Bemrose. Effect function it is not listed in the link's list you posted – Sergio del Amo May 11 '09 at 16:24
  • @Steerpike. Do I have to download effects.core.js? and where from? – Sergio del Amo May 11 '09 at 16:25
  • 2
    This is available in jQuery UI: http://docs.jquery.com/UI/Effects/Highlight#overview – Matt Scilipoti Oct 22 '10 at 20:54
  • 7
    As an update to previous comments, you no longer include effects.core.js and effects.highlight.js (and those old URLs no-longer work). The new way to include this is to include the jquery-ui library: http://code.jquery.com/ui/1.10.4/jquery-ui.min.js – Sean Colombo Feb 13 '14 at 20:13
68

I loved Sterling Nichols answer, since it was lightweight and didn't require a plugin. However, I discovered it didn't work with floating elements (i.e. such as when the element is "float:right"). So I re-wrote the code to display the highlight properly no matter how the element is positioned on the page:

jQuery.fn.highlight = function () {
    $(this).each(function () {
        var el = $(this);
        $("<div/>")
        .width(el.outerWidth())
        .height(el.outerHeight())
        .css({
            "position": "absolute",
            "left": el.offset().left,
            "top": el.offset().top,
            "background-color": "#ffff99",
            "opacity": ".7",
            "z-index": "9999999"
        }).appendTo('body').fadeOut(1000).queue(function () { $(this).remove(); });
    });
}

Optional:
Use the following code if you also want to match the border-radius of the element:

jQuery.fn.highlight = function () {
    $(this).each(function () {
        var el = $(this);
        $("<div/>")
        .width(el.outerWidth())
        .height(el.outerHeight())
        .css({
            "position": "absolute",
            "left": el.offset().left,
            "top": el.offset().top,
            "background-color": "#ffff99",
            "opacity": ".7",
            "z-index": "9999999",
            "border-top-left-radius": parseInt(el.css("borderTopLeftRadius"), 10),
            "border-top-right-radius": parseInt(el.css("borderTopRightRadius"), 10),
            "border-bottom-left-radius": parseInt(el.css("borderBottomLeftRadius"), 10),
            "border-bottom-right-radius": parseInt(el.css("borderBottomRightRadius"), 10)
        }).appendTo('body').fadeOut(1000).queue(function () { $(this).remove(); });
    });
}
Doug S
  • 10,146
  • 3
  • 40
  • 45
65

The jQuery effects library adds quite a bit of unneeded overhead to your app. You can accomplish the same thing with jQuery only. http://jsfiddle.net/x2jrU/92/

jQuery.fn.highlight = function() {
   $(this).each(function() {
        var el = $(this);
        el.before("<div/>")
        el.prev()
            .width(el.width())
            .height(el.height())
            .css({
                "position": "absolute",
                "background-color": "#ffff99",
                "opacity": ".9"   
            })
            .fadeOut(500);
    });
}

$("#target").highlight();
Sterling Nichols
  • 1,518
  • 2
  • 18
  • 22
  • 4
    Thanks, This is better and I was looking for something with which I can avoid including complete UI core which was completely unnecessary. – deej Sep 07 '12 at 10:29
  • You rock. Exactly what I was looking for, without adding another plugin. And I like that it does an actual overlay of the entire element, as opposed to just changing the element background color (which could be covered up by text, buttons, etc). – Doug S Oct 15 '12 at 05:32
  • 3
    UPDATE: This code will often fail when trying to highlight floating elements (i.e. when the element is "float:right"). So I re-wrote the code to display the highlight properly no matter how the element is positioned on the page: http://stackoverflow.com/a/13106698/1145177 – Doug S Oct 28 '12 at 05:49
  • Thanks for the update Doug.. I'll have to update my own libraries. – Sterling Nichols Dec 14 '12 at 16:29
  • This is great except on small problem, the container that gets added is not removed after the YFT so calling this repeatedly on the same element will litter the DOM. I've forked the original fiddle and added the code to remove the YFT container after the animation ends. http://jsfiddle.net/monkeymojo/HvRTm/3/ – Brian Antonelli Jan 28 '13 at 19:34
  • I think you are missing a semi-colon at the end of your function definition. Shouldn't cause a problem in most circumstances but it would probably fail JSLint. ```jQuery.fn.highlight = function() { ... }``` **;** – Aaron D Mar 09 '13 at 19:27
  • 2
    Nice lightweight solution - works really well. I found my highlights didn't include the element padding though, so I used `.width(el.outerWidth())` and `.height(el.outerHeight())` to highlight the whole of my form fields. – Mark B Jul 05 '13 at 14:56
  • I think there should be a callback in fade out, to remove generated div. – Bharat Patil Feb 13 '15 at 05:11
  • thanks Mark for that padding solutions. I have noticed 1 other problem, the z-index of the generated div can be higher than the existing div, so i added the following line after the opacity: '"z-index": -1000' to make sure the generated div is at the back – WtFudgE Aug 03 '15 at 03:42
  • Added return $(this); to the code, makes it able to call other functions after the .highlight() is called – WickStargazer Mar 11 '16 at 04:28
15

Define your CSS as follows:

@-webkit-keyframes yellowfade {
    from { background: yellow; }
    to { background: transparent; }
}

@-moz-keyframes yellowfade {
    from { background: yellow; }
    to { background: transparent; }
}

.yft {
    -webkit-animation: yellowfade 1.5s;
       -moz-animation: yellowfade 1.5s;
            animation: yellowfade 1.5s;
}

And just add the class yft to any item $('.some-item').addClass('yft')

Demo: http://jsfiddle.net/Q8KVC/528/

Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101
8
(function($) {
  $.fn.yellowFade = function() {
    this.animate( { backgroundColor: "#ffffcc" }, 1 ).animate( { backgroundColor: "#ffffff" }, 1500 );
  }
})(jQuery);

Should do the trick. Set it to the yellow, then fade it to white

8

I just solved a problem similar to this on a project I was working on. By default, the animate function cannot animate colors. Try including jQuery Color Animations.

All the answers here use this plugin but no one mentions it.

Travis
  • 12,001
  • 8
  • 39
  • 52
3

Actually, I have a solution that only needs jQuery 1.3x, and no aditionnal plugin.

First, add the following functions to your script

function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) {
    var delta = maxValue - minValue;
    var stepp = minValue+(Math.pow(((1 / totalSteps)*actualStep),powr)*delta);
    return Math.ceil(stepp)
}

function doBGFade(elem,startRGB,endRGB,finalColor,steps,intervals,powr) {
    if (elem.bgFadeInt) window.clearInterval(elem.bgFadeInt);
    var actStep = 0;
    elem.bgFadeInt = window.setInterval(
        function() {
            elem.css("backgroundColor", "rgb("+
                easeInOut(startRGB[0],endRGB[0],steps,actStep,powr)+","+
                easeInOut(startRGB[1],endRGB[1],steps,actStep,powr)+","+
                easeInOut(startRGB[2],endRGB[2],steps,actStep,powr)+")"
            );
            actStep++;
            if (actStep > steps) {
            elem.css("backgroundColor", finalColor);
            window.clearInterval(elem.bgFadeInt);
            }
        }
        ,intervals)
}

Next, call the function using this:

doBGFade( $(selector),[245,255,159],[255,255,255],'transparent',75,20,4 );

I'll let you guess the parameters, they are pretty self explanatory. To be honest the script is not from me, I took it on a page then changed it so it works with the latest jQuery.

NB: tested on firefox 3 and ie 6 (yes it works on that old thing too)

2

this is my solution for the problem. it works excelent. it passes jslint error validation and also works decent in IE8 and IE9. Of course you can tweak it to accept color codes and callbacks:

jQuery.fn.highlight = function(level) {

  highlightIn = function(options){

    var el = options.el;
    var visible = options.visible !== undefined ? options.visible : true;

    setTimeout(function(){
      if (visible) {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 < 1) {
          options.iteration += 2;
          highlightIn(options);
        }
      } else {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 > 0) {
          options.iteration -= 2;
          highlightIn(options);
        } else {
          el.css('background-color', '#fff');
        }
      }
    }, 50);
  };

  highlightOut = function(options) {
    options.visible = false;
    highlightIn(options);
  };

  level = typeof level !== 'undefined' ? level : 'warning';
  highlightIn({'iteration': 1, 'el': $(this), 'color': level});
  highlightOut({'iteration': 10, 'el': $(this), 'color': level});
};
many
  • 21
  • 1
  • 1
    what benefit does this have over the jQuery highlight? http://docs.jquery.com/UI/Effects/Highlight – Nathan Koop Oct 29 '12 at 13:11
  • 1
    well in my case i couldn't use Jquery ui. so i was left with fixing a solution with only Jquery. – many Oct 29 '12 at 19:11
2
function YellowFade(selector){
   $(selector)
      .css('opacity', 0)
      .animate({ backgroundColor: 'Yellow', opacity: 1.0 }, 1000)
      .animate({ backgroundColor: '#ffffff', opacity: 0.0}, 350, function() {
             this.style.removeAttribute('filter');
              });
}

The line this.style.removeAttribute('filter') is for an anti-aliasing bug in IE.

Now, call YellowFade from wherever, and pass your selector

YellowFade('#myDivId');

Credit: Phil Haack had a demo showing exactly how to do this. He was doing a demo on JQuery and ASPNet MVC.

Take a look at this video

Update: Did you take a look at the video? Forgot to mention this requires the JQuery.Color plugin

Vin
  • 6,115
  • 4
  • 41
  • 55
  • The next error is being thrown by the filter line. I am using yellow fade in a table row element (tr) "this.style.removeAttribute is not a function [Break on this error] this.style.removeAttribute('filter');" – Sergio del Amo May 11 '09 at 16:37
2

I hated adding 23kb just to add effects.core.js and effects.highlight.js so I wrote the following. It emulates the behavior by using fadeIn (which is part of jQuery itself) to 'flash' the element:

$.fn.faderEffect = function(options){
    options = jQuery.extend({
        count: 3, // how many times to fadein
        speed: 500, // spped of fadein
        callback: false // call when done
    }, options);

    return this.each(function(){

        // if we're done, do the callback
        if (0 == options.count) 
        {
            if ( $.isFunction(options.callback) ) options.callback.call(this);
            return;
        }

        // hide so we can fade in
        if ( $(this).is(':visible') ) $(this).hide();

        // fade in, and call again
        $(this).fadeIn(options.speed, function(){
            options.count = options.count - 1; // countdown
            $(this).faderEffect(options); 
        });
    });
}

then call it with $('.item').faderEffect();

Corey
  • 1,977
  • 4
  • 28
  • 42
1

I simply used...

<style>
tr.highlight {
background: #fffec6;
}
</style>


<script>
//on page load, add class
$(window).load(function() {
$("tr.table-item-id").addClass("highlight", 1200);
}); 

//fade out class
setTimeout(function(){
$("tr.table-item-id").removeClass("highlight", 1200);   
}, 5200);

</script>
BENN1TH
  • 2,003
  • 2
  • 31
  • 42
1

YOU NEED ONLY HTML TO DO THIS. No CSS or JS required!

Suppose you have a text on a certain page that you want to temporarily "highlight and show" to users upon visiting the page.

And let the content on that page to be highlighted be a h2 tag and a p tag content as shown below:


<h2>Carbon Steel for Blacksmithing</h2>

<p>The vast majority of blacksmithing uses low and medium carbon steels. High carbon steel, sometimes called “carbon tool steel,” is very hard, and difficult to bend or weld; it gets very brittle once it’s been heat-treated.</p>
<p>You can buy steel, or you can find and recycle. I prefer the later.</p>

Given below: a link that will ACTUALLY highlight the content that is shown above. Whenever a user clicks this link... they get redirected to the page to the same spot where where the content is, and also the text is highlighted!

https://stackoverflow.com/questions/848797/yellow-fade-effect-with-jquery/63571443#:~:text=Carbon%20Steel%20for%20Blacksmithing,you%20can%20find%20and%20recycle.

To give a live example: Follow the link given above to see the highlight effect upon the content that I mentioned in the link.

ashuvssut
  • 1,725
  • 9
  • 17
  • But it doesn't works on the stack page you gave above. Though, I too have seen it in action on SERPs. – Sujal Jain Feb 01 '21 at 15:05
  • I dont know why its not working for you...but when I put the link and pressed enter..the desired effect came out. can you tell how did you use that link i showed you above? – ashuvssut Feb 01 '21 at 15:22
  • Dude, I tried on different occassions, like in chrome and opera, it is working good. It does not works with microsoft edge, brave nightly or brave, firefox and yandex. Anyways, nice and easy solution for any beginner or low-experienced coder. – Sujal Jain Feb 01 '21 at 15:38
1

This is a non-jQuery option you can use for the color fade effect. In the array "colors", you add the transition colors you need from the initial color until the last color. You can add as much colors as you want.

   <html lang="en">
   <head>
   <script type="text/javascript">
  //###Face Effect for a text box#######

var targetColor;
var interval1;
var interval2;
var i=0;
var colors = ["#FFFF00","#FFFF33","#FFFF66","#FFFF99","#FFFFCC","#FFFFFF"];

function changeColor(){
    if (i<colors.length){
        document.getElementById("p1").style.backgroundColor=colors[i];
        i++;
    } 
    else{
        window.clearInterval(interval1);
        i=0;
    }
}
addEventListener("load",function(){
    document.getElementById("p1").addEventListener("click",function(e){
        interval1=setInterval("changeColor()",80);              

    })
});
</script>

</head>

<body>
<p id="p1">Click this text box to see the fade effect</p>

<footer>
 <p>By Jefrey Bulla</p>
</footer>
</div>
</body>
</html> 
Jefrey Bulla
  • 181
  • 2
  • 5
0

If you'd like to try an alternative yellow fade technique that does not depend on jQuery UI .effect, you could position a yellow (or another color) div behind your content and use the jQuery .fadeOut().

http://jsfiddle.net/yFJzn/2/

<div class="yft">
    <div class="content">This is some content</div>
    <div class="yft_fade">&nbsp;</div>
</div>

<style>
  .yft_fade {
      background-color:yellow;
      display:none;
  }
  .content {
      position:absolute;
      top:0px;
  }
</style>

<script>
  $(document).ready(function() {
      $(".yft").click(function() {
          $(this).find(".yft_fade").show().fadeOut();
      });
  });​
</script>
tim-montague
  • 16,217
  • 5
  • 62
  • 51
0

A simple/raw script for a "yellow fadeout", no plugins except jquery itself. Just setting background with rgb(255,255,highlightcolor) in a timer:

<script>

    $(document).ready(function () {
        yellowFadeout();
    });

    function yellowFadeout() {
        if (typeof (yellowFadeout.timer) == "undefined")
            yellowFadeout.timer = setInterval(yellowFadeout, 50);
        if (typeof (yellowFadeout.highlightColor) == "undefined")
            yellowFadeout.highlightColor = 0;
        $(".highlight").css('background', 'rgb(255,255,' + yellowFadeout.highlightColor + ')');
        yellowFadeout.highlightColor += 10;
        if (yellowFadeout.highlightColor >= 255) {
            $(".highlight").css('background','');
            clearInterval(yellowFadeout.timer);
        }
    }
</script>
Johan Danforth
  • 4,469
  • 6
  • 37
  • 36