Adding Event Listeners on Elements - Javascript - 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>

Related

Incrementing an int via a button returns unintended behavior.

I have a variable that i wish to increment. If i do it like this, it works fine:
var curTrial = 0;
function inc(x) {
x++;
return x;
}
function show () {
document.write(curTrial)
curTrial = inc(curTrial);
}
show();show();show();show()
This results in 0123, as expected/intended.
However, if i spice it up a little with a button, it'll behave strangely.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
</head>
<body>
<div id="box" style="text-align:center">
<div id="startTrial">Press any key to start the next trial</div>
<button id="next"type="button">Submit</button>
</div>
<script>
var curTrial = 0;
function inc(x) {
x++;
return x;
}
function RunTrial() {
prompt(curTrial);
curTrial = inc(curTrial);
$('#box').show();
$("#next").click(function(f) { StartExperiment(); });
}
function StartExperiment() {
$('#box').show();
$("#next").click(function(f) { RunTrial(); });
}
StartExperiment()
</script>
</div>
</body>
</html>
Now, the value still increments with one at a time, but i would expect it to be called once for each button press. Instead, it appears to be called double the amount of last time (once, twice, four times, eight times etc)
You are attaching a click event handler each time inside the function RunTrial() and StartExperiment()
Sloution
Remove the event handlers from the funtion and put them in $(document).ready block.
Use $("#next").unbind( "click" ); to unbind the event.
Well first one is preferable.
var curTrial = 0;
$(document).ready(function(){
$("#next").click(function(f) { RunTrial(); });
});
function inc(x) {
x++;
return x;
}
function RunTrial() {
prompt(curTrial);
curTrial = inc(curTrial);
$('#box').show();
$("#next").click(function(f) { StartExperiment(); });
}
function StartExperiment() {
$('#box').show();
}
StartExperiment();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
</head>
<body>
<div id="box" style="text-align:center">
<div id="startTrial">Press any key to start the next trial</div>
<button id="next"type="button">Submit</button>
</div>
</div>
</body>
</html>
It's because in RunTrial(), you call StartExperiment(), which adds a new click listener to the #next button, so every time you click it, you're adding on a new click listener. If you just remove that line, you'll see that it works as intended (only one prompt per click).
var curTrial = 0;
function inc(x) {
x++;
return x;
}
function RunTrial() {
curTrial=prompt(curTrial);
curTrial = inc(curTrial);
$('#box').show();
$("#next").click(function(f) { StartExperiment(); });
}
function StartExperiment() {
$('#box').show();
$("#next").click(function(f) { RunTrial(); });
}
StartExperiment()
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
</head>
<body>
<div id="box" style="text-align:center">
<div id="startTrial">Press any key to start the next trial</div>
<button id="next"type="button">Submit</button>
</div>
</div>
</body>
</html>
Remove $("#next").click(function(f) { StartExperiment(); }); from runTrial() function.
What you are doing is binding a click event everytime RunTrial() is called.
clicking on submit button, will trigger runTrial function as many times the number of click events binded to it.
Just bind the event once and it will work everytime the button is clicked

how to get id of any control using javascript?

I have an html page with various textbox and button
then I added this javascript
window.onload = function () {
window.addEventListener('click', function (evt) {
alert(this.id);
}, false);
};
my goal is to return the ID of the control clicked by the user (as an alert)?
eventually I will add more to this. but as an alert is ok for now. Thank you
Use the target of the event. Here's a runnable sample:
window.onload = function () {
window.addEventListener('click', function (evt) {
alert(evt.target.id);
}, false);
};
<input id="button" type="button" value="button" />
<input id="text" type="text" />
You have added eventListener to the window object.So "this"keyword refers windows object and not your buttons.check for ev.srcElement
window.onload = function () {
window.addEventListener('click', function (evt) {
alert(evt.srcElement.id);
}, false);
};

Add event handler to HTML element using 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/

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; });

Can I have two JavaScript onclick events in one element?

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Categories