click on a div with regular javascript

心已入冬 提交于 2019-12-01 19:54:43

If you just want to bind one function to the element, you could use

var element = document.getElementById("el"); //grab the element
element.onclick = function() { //asign a function
//code
}

but if you need to attach more than one event, you should use addEventListener (eveything except IE) and attachEvent (IE)

if(element.addEventListener) {
element.addEventListener("click", function() {});
} else { 
element.attachEvent("onclick", function() {})
}

The click() function is built in JavaScript, not jQuery.

HTMLElementObject.click()

Source.

Here's an article by John Resig (creator of jQuery) on how to do this very thing. It's basically his entry into a contest (that he won) on how to rewrite addEvent().

var d = document.getElementById("test");
d.onclick = function(){alert('hi');};
var divElement = document.getElementById('section');

divElement.addEventListener('click', function () {
  alert('div clicked');
},false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!