Monday, November 21, 2011

Triggering Associated Event


You can trigger an event of a HTMLElement calling the onclick event of the element.

Let's say, you have <div><ul><li><dl><dd parent="MotorCycle">Honda VFR1200Fdd>dl>li>ul>div>

Then you can do
<div onclick="triggerFilterEvent(this)">Honda VFR1200Fdiv>

The reason you do is so that you don't have duplicated method calls.  The parameters allow you to traverse through its DOM tree.  

function triggerFilterEvent(object1) {
    var category = $(object1).attr("parent");
    var value = $(object1).text();
    var root = $("div");
    var dls = $(root).find("ul li dl");
    var dds = $(dls).find("dd[parent='" + category + "']");
    for (var x = 0; x < $(dds).length; x++) {
        var dd = $(dds)[x];
        if (dd.innerText === value) {
            $(dd).click();
        }
    }
}
you could do var dd =$("div ul li dl dd[parent='"+category +"']").click(); but on IE version < 9, the code would encounter problems.
You also note that I did the for loop instead of the jQuery.each().


No comments: