Sunday, 24 November 2013

Highlight HTML Element on page

Demo: Click on Highlight



How
you
doin?


Code: How to achieve this effect :

JavaScript:
var transitionTime = 1000,

transitionEffect = 'box-shadow 1s',

shadowEffect = 'inset 0px 0px 7px 0px #FF0000, 0px 0px 7px 0px #FF0000',

removeShadow = function(element) {
    $(element).css({
        boxShadow: 'inset 0px 0px 0px 0px #000, 0px 0px 0px 0px #000' 
    });
},

resetShadow = function(element) {
    $(element).css({
       boxShadow: ''
    });
},

removeTransition = function(element) {
    $(element).css({
        transition: ''
    });
},

highlight = function(element) {
    $(element).css({
        transition: transitionEffect, boxShadow: shadowEffect 
    });
    setTimeout(function() {
        removeShadow(element);
        setTimeout(function() {
            resetShadow(element);
            removeTransition(element);
        }, transitionTime);
    }, transitionTime );
},

highlightFunction = function() {
    var elements = $(".highlight-ele");
    for(var i = 0; i < elements.length; i++) {
        highlight(elements[i]);
    }
}

HTML:
<div class="container-div">
    <div class="margin-div">
        <div class="inline-div highlight-ele" id="div1">
            How
        </div>

        <div class="inline-div highlight-ele" id="div2">
            you
        </div>

        <div class="inline-div highlight-ele" id="div3">
            doin?
        </div>
   </div>
   <div class="margin-div">
        <div class="new-div">
            <input class="highlight-ele" style="border : 1px solid black">                   </input>
        </div>
   </div>
   <div class="margin-div">
        <button onclick="highlightFunction()" style="height: 25px; width: 153px;">
            Highlight
        </button>
   </div>
</div>


CSS:
.inline-div{
    display: inline-block;
    text-align: center;
    height: 50px;
    width: 50px;
    vertical-align: middle;
    line-height: 50px;
}

.new-div {
    display: inline-block;
}

.margin-div {
    margin:10px 10px 10px 10px;
}

.container-div {
    margin: 0px auto;
    width: 178px;
    border: 1px groove;
}





jquery plugin:

I have created a jquery plugin to achieve the same effect Highlighter Plugin for jquery

Just include the js in your code and call highlight method on your selector $(".highlight-ele").highlight();

It is hosted on Github : jquery-highlighter on GitHub