Stop propagation through html's "onclick" event and JS

tegowai picture tegowai · Aug 6, 2014 · Viewed 13.1k times · Source

This is my html chunk

<tr>
    <td class="c_menu" id="bat_light">
        <a href="someLink/file.html#"  onclick="OpenItem('light');return false;">sometitle</a>
    </td>
    <td class="c_menu"  id="bat_econom">
        <a href="someLink/file.html#" onclick="OpenItem('econom');return false;">
    sometitle</a>
    </td>
    <td class="c_menu"  id="bat_standart">
        <a href="someLink/file.html#" onclick="OpenItem('standart');return false;">
    sometitle</a>
    </td>
    <td class="c_menu"  id="bat_premium">
        <a href="someLink/file.html#" onclick="OpenItem('premium');return false;">
    sometitle</a>
    </td>
</tr>

and this is JavaScript intro at the top

function OpenItem(name){
    var blocks = ['light', 'econom', 'standart', 'premium'];
    for(var i = 0; i < blocks.length; i++){
        if (blocks[i] == name){
            document.getElementById('bat_'+blocks[i]).className="c_menu active";
            document.getElementById('descr_'+blocks[i]).style.display="block";
            document.getElementById('tab_'+blocks[i]).style.display="block";
        }
        else{
            document.getElementById('bat_'+blocks[i]).className="c_menu";
            document.getElementById('descr_'+blocks[i]).style.display="none";
            document.getElementById('tab_'+blocks[i]).style.display="none";
        }
    }
}

I understand how to fix page default topscrolling in JQuery,but helpless in this case with simple JS. Rewriting the code to JQuery unacceptable. Tried to set 'this' as second argument to function and then event.preventDefault() - does not work.

Answer

Ajinkya picture Ajinkya · Aug 6, 2014

To stop event propagation you have to use the following method.

event.stopPropagation()

The event object is passed by default to the handler function for any event. So, instead of defining event handlers inline, define in them a separate script file. The event handlers should be attached once the DOM has loaded. You can follow the pattern shown in below code snippet.

//handles the click event
function handleClick(ev) {
    console.log('clicked on ' + this.tagName);
    ev.stopPropagation();
}
window.onload = function() {    
    var links = document.getElementsByTagName('a');

    //attaches the event handler to all the anchor tags
    Array.prototype.forEach.call(links, function(elem) { 
        elem.onclick = handleClick; 
    });
}

Reading List