Add event handler to HTML element using javascript - javascript

I want to add an event handler to a paragraph for when any user clicks on it. For example, I have a paragraph which would show an alert when a user clicks it, but without using "onclick" on HTML.
<p id="p1">This is paragraph Click here..</p>
<a href="http://www.google.com" id="link1" >test</a>
document.getElementById('p1').onmouseover = paragraphHTML;

You can add event listener.
Smth. like this:
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
(thanks #Reorx)
Explanation Here
Complete code (tested in Chrome&IE7):
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<script type="text/javascript">
window.onload =function (){
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
};
function yourFunction(){
alert("test");
}
</script>
</head>
<body>
<p id="p1">test</p>
</body>
</html>

To suit most situations, you can write a function to handle this:
var bindEvent = function(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on'+type, handler);
}
}

Add a tabIndex attribute to your p element, then you can use the onfocus function.
demo: http://jsfiddle.net/9y7CL/

Related

How to pass click location to a function as parameter in JS? [duplicate]

so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?
<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}
make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>
you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}

Right click stop propagation

How do I stop the propagation for right click events in javascript, so parent elements do not detect them at all?
When I click the link in the following html, left clicks are not detected, but right clicks are detected by the document element as 'click' events instead of 'contextmenu' events. I've tried to attach event listeners to mousedown, contextmenu, but to no success.
[EDIT] Changing the code to contextmenu works on chrome but not firefox (v23.0.1), this is probably a firefox bug.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="application/javascript;version=1.8">
function log(s){
document.getElementById('log').innerHTML+=s+'<br/>';
}
window.onload=function(){
document.addEventListener('click',function(e){
log('click detected');
},false);
let link=document.querySelector('a#link');
//click only cares about left clicks
link.addEventListener('click',function(e){
e.stopPropagation();
return false;
},false);
};
</script>
</head>
<body>
<a id="link" href="javascript:void(0);">Link</a>
<div id="log"></div>
</body>
</html>
The 'right click' event is called the 'contextmenu' event.
http://www.quirksmode.org/dom/events/contextmenu.html
Example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function log(s){
document.getElementById('log').innerHTML+=s+'<br/>';
}
window.onload=function(){
document.addEventListener('click',function(e){
log('click detected');
},false);
document.addEventListener('contextmenu', function(e){
log('right-click detected');
}, false);
var link=document.querySelector('a#link');
link.addEventListener('click',function(e){
e.stopPropagation();
return false;
},false);
link.addEventListener('contextmenu',function(e){
e.stopPropagation();
return false;
},false);
};
</script>
</head>
<body>
<a id="link" href="javascript:void(0);">Link</a>
<div id="log"></div>
</body>
</html>
Chrome won't execute script tags, including a version , for some reason, so i replaced let with var...
Stopping the propagation of a contextmenu event triggered from a#Link to document works fine for me, in Chrome and Firefeox, here is the example i used.
Edit
the contextmenu events are detected by the document element as click events instead.
In this case you can use a mousedown event, and add the condition event.which === 3
I updated the example, and added an example on JSBin
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<a id="link" href="javascript:void(0);">Link</a>
<div id="log"></div>
<script type="application/javascript">
window.onload = function () {
var link = document.querySelector('a#link');
function log(s) {
document.getElementById('log').innerHTML += s + '<br/>';
}
document.addEventListener('mousedown', function (e) {
if (e.which === 3) {
var src = e.target || e.srcElement;
log((src.nodeName === 'A' ? 'bubbled' : 'direct') + ' contextmenu on document detected');
}
}, false);
link.addEventListener("mousedown", propagate);
function propagate(e) {
if (e.which === 3) {
log("contextmenu on link, propagating");
link.removeEventListener("mousedown", propagate);
link.addEventListener("mousedown", nopropagate);
}
}
function nopropagate(e) {
if (e.which === 3) {
log("contextmenu on link, nopropagating");
e.stopPropagation();
}
}
}
</script>
</body>
</html>
Now rightclicking in the following order gives us these outputs.
rightclick on document
rightclick on link (propagates on first click)
rightclick on link (doesn't propagate)
Screenshots are from Firefox 20.0

How to get the element that fired the "onclick" event

<script>
function clicky(e){
console.log(e) //the clicked element
}
</script>
<span onClick="clicky(this)">Clickable</span>
In the script above, the console.log(e) will give me the <span> that I clicked on.
Is there any way that I could omit the clicky(this) and still get the element?
It's because I don't want to put (this) all over the document.
Any answer are welcomed.
See this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="foo" style="background:blue; width:100px; height:100px">
<script>
function clicky(e){
console.log(e);
}
var foo = document.getElementById("foo");
foo.onclick = function(e){clicky((e || window.event).target);}
</script>
</body>
</html>
You could try this, not tested though.
var spans = document.getElementsByTagName('span');
spans.attachEvent('click'.'clicky');
function clicky(e){
console.log(e) //the clicked element
}
or
var spans = document.getElementsByTagName('span');
for (i in spans)
{
spans[i].attachEvent('click'.'clicky');
}
function clicky(e){
console.log(e) //the clicked element
}
function clicky(e, elem){
<span onClick="clicky(event, this)">Clickable</span>
Or you could use Prototype or jQuery or any other library. I would improve your life.

Adding Event Listeners on Elements - Javascript

Are there ways for me to listen for onblur or onclick events in javascript from an onload function? instead of doing it in the element itself.
<input type="button" id="buttonid" value="click" onclick="func()">
to become something like
function onload() {
var button = document.getElementById("buttonid");
button.addEventListener("onclick", function() { alert("alert");});
}
EDIT
<html>
<head>
<script>
function onload() {
var button = document.getElementById("buttonid");
if(button.addEventListener){
button.addEventListener("click", function() { alert("alert");});
} else {
button.attachEvent("click", function() { alert("alert");});
};
};
window.onload = onload;
</script>
</head>
<body>
<input type="button" id="buttonid" value="click">
</body>
</html>
UPDATE
<script type="text/javascript">
function on_load() {
var button = document.getElementById("buttonid");
if(button.addEventListener){
button.addEventListener("click", function() { alert("alert");});
} else {
button.attachEvent("click", function() { alert("alert");});
};
};
window.onload = on_load();
</script>
The way you are doing it is fine, but your event listener for the click event should be like this:
button.addEventListener("click", function() { alert("alert");});
Notice, the click event should be attached with "click", not "onclick".
You can also try doing this the old way:
function onload() {
var button = document.getElementById("buttonid");
// add onclick event
button.onclick = function() {
alert("alert");
}
}
Update 1
You need to also monitor for IE < 9, because those Vs use attachEvent(). Attach the event like this, so it will work with dinosaur browsers:
if(button.addEventListener){
button.addEventListener('click', function() { alert("alert");});
} else if(button.attachEvent){ // IE < 9 :(
button.attachEvent('onclick', function() { alert("alert");});
}
Update 2
Based on your edit, this should work works just fine.
<html>
<head>
<script type="text/javascript">
function init() {
var button = document.getElementById("buttonid");
if(button.addEventListener){
button.addEventListener("click", function() { alert("alert");}, false);
} else if(button.attachEvent){
button.attachEvent("onclick", function() { alert("alert");});
}
};
if(window.addEventListener){
window.addEventListener("load", init, false);
} else if(window.attachEvent){
window.attachEvent("onload", init);
} else{
document.addEventListener("load", init, false);
}
</script>
</head>
<body>
<input type="button" id="buttonid" value="click">
</body>
</html>
Please, do not use window.onload = on_load();, this will prevent all other onload event listeners from getting fired, or you are risking for your event listener to get overwritten. Consider attaching the onload event the way I am suggesting above.
The better way it's used DOM (works perfectly) like this.
Firs write Yours function/class and use it in:
document.addEventListener('DOMContentLoaded', function(){
// put here code
});
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunc(){ alert('Hellow there!'); }
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('mybtn').addEventListener('click', myFunc);
});
</script>
</head>
<body>
<button id="mybtn">Cklik!</button>
</body>
</html>
It's doesn't matter where You used this few lines. You can put it in head or in body.
A better way to dynamically add event handlers would be to use a JavaScript library like jQuery, because it will abstract away any browser-specific details.
to further my conversation in the comments section...
#simplified, try putting this in the < head > of your page
<script type="text/javascript">
function my_onload() {
var button = document.getElementById("buttonid");
if(button.addEventListener){
button.addEventListener("click", function() { alert("alert");}, true);
}else{
button.attachEvent("click", function() { alert("alert");});
};
};
window.onload = my_onload;
</script>
and see what happens. also, please advise us on which browser you are using.
https://developer.mozilla.org/en/DOM/element.addEventListener
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
var required = document.getElementById("required").value;
if (required===null || required==="") {
alert("Please make sure all required field are completed");
}
else {
alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
}
});
</script><html>
<body>
<div id="popup">
<textarea cols="30" rows="2" name="required" id="required"></textarea>
<input type="submit" id="click" value="Submit">
<input type="reset" value="Reset" />
</div>
</body>
</html>

Add event listener to all objects except for a few selected?

I'm trying to add event listener to all objects except for a few selected (the selected also have arbitrary child elements in arbitrary levels)?
I have asked this question before, but I didn't really got an answer to it. I have came close to solve it. Could you please help me with debugging it?
I'm adding an event listener to the body element called bodylistener and an event listener to the few selected elements called selectedElementsMarkTrue. The few selected elements that I don't want to execute some code, the listener selectedElementsMarkTrue performs prior to bodylistener with setTimeout function. selectedElementsMarkTrueset the variable selectedElements to true and bodylistenerchecks if selectedElements is true before execute some code. There is still something wrong with my code:
var selectedElements = false;
var bodylistener = function(){
window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
(function(){
if(selectedElements == false){
//Do some stuff
}else{
selectedElements = false;
}
});
}, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);
I can't get the setTimeout function to execute the underlying code?
Sounds like you want behavior something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
document.body.addEventListener("click", function(e) {
var el = e.target;
do {
if (el.hasAttribute && el.hasAttribute("data-nofire")) {
return;
}
} while (el = el.parentNode);
alert('do stuff');
}, true);
}, false);
</script>
</head>
<body>
<p><span>click me</span></p>
<p data-nofire><span>click me</span></p>
<p data-nofire>click me</p>
<p>click me</p>
</body>
</html>
Or, you could do it something like Naren suggested:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
var nofire = document.getElementsByClassName("nofire");
for (var i = 0; i < nofire.length; ++i) {
nofire[i].addEventListener("click", function(e) {
e.stopPropagation();
}, true);
}
document.body.addEventListener("click", function(e) {
alert('do stuff');
}, false);
}, false);
</script>
</head>
<body>
<p><span>click me</span></p>
<p class="nofire"><span>click me</span></p>
<p class="nofire">click me</p>
<p>click me</p>
</body>
</html>
prevent event propagation by handling elements click event
$('#dontAddEventListener1, #dontAddEventListener2').click( function(event){ event.preventDefault(); return false; });

Categories