In this tutorial i am gonna show you how a javascript function can be hooked to a HTML element with its predefined class or id attribute. We are going to use class attribute here because we may want to have multiple elements of the same kind where in we want the javascript functions to be hooked. We can have same class names for multiple html elements but there should be unique ID for each HTML element.

         <div>
            <a href="#" class="overlay">Show a hidden div</a>
        </div>
        <div>
            <a href="http://blog.realin.co.in" >Visit my blog</a>
        </div>
        <div style="display:none;background-color:yellow;" id="mydiv">I am the hidden div</div>
function hookFunc(){
 
                var d=document.getElementById("mydiv");
                var anchortags=document.getElementsByTagName("a");
                for(i=0;i<=anchortags.length;i++)
                {
 
 
                    var currentTag=anchortags[i];
                    if(currentTag.className=="overlay")
                    {
                        currentTag.onmouseover=function()
                        {
                            d.style.display="block";
                        }
                        currentTag.onmouseout=function()
                        {
                            d.style.display="none";
                        }
                    }
                }
 
 
            }

Explanation: I have two anchor tags in my HTML, one with the classname overlay and another without a class attribute or even with any class name we had not effected the code. The function getElementsByTagName(“a”) returns the array of all the anchor tags present in the document. We pick the anchor tag whose classname is overlay and then we hook the javascript function to that div.
You can see the working example below:

Demo

Hope you like it, if you have any feedback, questions leave a comment.
Cheers !!
Realin !

Share this post: