Search code examples
javascripthtmlclickable

How do I make the entire div clickable using plain javascript?


I don't need to write this in jQuery but I'm not versed enough in plain javascript to figure it out. Chris Coyier wrote a nice explanation of what I'm talking about here.

The reason I want to convert it is because I don't need to include an entire jQuery library for this one piece of code. I can save that extra request by using plain old javascript.

This is the example code that I want to convert:

$(document).ready(function() {
    $(".featured").click(function(){
        window.location=$(this).find("a").attr("href"); return false;
    });
});

Here's what I've come up with so far:

document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll("div.feature").click(function(){
        window.location=$(this).find("a").setAttribute("href"); 
        return false;
    });
});

One thing which isn't correct in this, as far as I know, are the querySelectorAll, which is looking for just a div element, right? The other thing is the $(this), which I don't know how to translate into plain javascript.


Solution

  • You can select with this.querySelectorAll(...):

    IE8:

    window.onload = function() {
        // get all dom elements with class "feature"
        var aFeatures = document.querySelectorAll(".feature");
        // for each selected element
        for (var i = 0; i < aFeatures.length; i++) {
            // add click handler
            aFeatures[i].onclick = function() {
                // get href of first anchor in element and change location
                window.location = this.querySelectorAll("a")[0].href;
                return false;
            };
        }
    };
    

    IE9 and other current browser:

    document.addEventListener("DOMContentLoaded", function() {
        // get all dom elements with class "feature"
        var aFeatures = document.querySelectorAll(".feature");
        // for each selected element
        for (var i = 0; i < aFeatures.length; i++) {
            // add click handler
            aFeatures[i].addEventListener('click', function() {
                // get href of first anchor in element and change location
                window.location = this.querySelectorAll("a")[0].href;
                return false;
            });
        }
    });
    

    === UPDATE ===

    For IE7 support you should add following (untested) script before (also see here):

    (function(d){d=document,a=d.styleSheets[0]||d.createStyleSheet();d.querySelectorAll=function(e){a.addRule(e,'f:b');for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)l[b].currentStyle.f&&c.push(l[b]);a.removeRule(0);return c}})()
    

    It is possible that it only supports document.querySelectorAll not element.querySelectorAll.