javascript add custom click event

function addEvent(elem, event, func) {
    if (elem.addEventListener) {
        elem.addEventListener(event, func, false);
    } else if (elem.attachEvent) {
        elem.attachEvent('on' + event, func);
    } else {
        elem['on' + event] = func;
function customFunc() {
    alert('custom Function');
var target = document.getElementById('target');
addEvent(target, 'click', customFunc);
var target2 = document.querySelector('.target2');
addEvent(target2, 'click', customFunc);
<p id="target">target element - click on me to see event</p>
<p class="target2">target2 element - click on me to see event</p>

Leave a Reply

Your email address will not be published. Required fields are marked *