Event listener - click and mouseover? - javascript

So basically I am trying to put together some simple event listeners. I've added a button with the ID of "btn" in my HTML file, and basically I want to add a mouseover event, and a click event. I know how to do this, however I want to alert when each event occurs. Is there a way to neaten my code and put this all into one function instead of two? I'm just not sure how I would create two separate alert statements otherwise on the same button. Thanks!

You can define a single function and then reference it as the 2nd argument to .addEventListener.
Example:
<button id='btn' value='some button'>some button</button>
<div id='placeholder'></div>
<script>
(function() {
var btn = document.getElementById("btn");
btn.addEventListener("click",doSomething,false);
btn.addEventListener("mouseover",doSomething,false);
})();
function doSomething(e) {
// example: update the div with the event type
var p=document.getElementById("placeholder");
p.innerHTML=e.type;
}
</script>
JSFIDDLE DEMO

Maybe this will help?
The code below can be improved by adding another argument to determine add/remove, turning the two functions into one, but you get the idea.
(function() {
var btn = document.getElementById("btn");
addEvent(btn, "click mouseover", handler);
function handler ( event ) {
alert("This is the " + event.type + " handler.");
}
})();
function addEvent ( element, event, fnc ) {
var events = event.split(/\s/),
evt = "";
while ( evt = events.shift() ) {
((element.addEventListener) ? element.addEventListener(evt, fnc, false) : element.attachEvent("on" + evt, fnc));
}
}
function removeEvent ( element, event, fnc ) {
var events = event.split(/\s/),
evt = "";
while ( evt = events.shift() ) {
((element.removeEventListener) ? element.removeEventListener(evt, fnc, false) : element.detachEvent("on" + evt, fnc));
}
}
<button id="btn" type="button">Click or Hover</button>

I think this is what you want:
var myfunc = function(event) {
var btn...
btn.addEventListener(event, function()...
}
After you can call it like this:
Myfunc("click");

Related

Handling "onclick" event with pure JavaScript

This is really straight forward but I'm still fairly new to JavaScript and just found JSFiddle. I'm trying to find the element with the getElementById() to disable and enable a button. What am I missing?
<form name="frm" >
<div id="chkObj">
<input type="checkbox" name="setChkBx" onclick="basicList.modifyAndEnableButton(this)"></input>
</div>
<div id="Hello">
<input type="button" name="btn" value="Hello"></input>
</div>
</form>
This is a list that I am using to add checkboxes because there is going to be more than one:
var basicList = {
'items': {},
'modifyAndEnableButton': function(obj1) {
var element = document.getElementsByName("btn");
if (obj1.checked == true && element.getAttribute('disabled') == false) {
element.getAttribute('disabled') = true;
this.addRecord(obj2);
} else if (element.getAttribute('disabled') == true) {
if (hasItems == false) {
element.getAttribute('disabled') = false;
}
}
}
};
http://jsfiddle.net/Arandolph0/E9zvc/3/
All browsers support this (see example here):
mySelectedElement.onclick = function(e){
//your handler here
}
However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)
mySelectedElement.addEventListener("click",function(e){
//your handler here
},false);
Here is a working example:
var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
button.disabled = "true";
},false);
And html:
<button id='myButton'>Hello</button>
(fiddle)
Here are some useful resources:
addEventListener on mdn
The click event in the DOM specification
Click example in the MDN JavaScript tutorial
Benjamin's answer covers quite everything. However you need a delegation model to handle events on elements that were added dynamically then
document.addEventListener("click", function (e) {
if (e.target.id == "abc") {
alert("Clicked");
}
});
For IE7/IE8
document.attachEvent('onclick', function (e) {
if (window.event.srcElement == "abc") {
alert("Clicked");
}
});
You have a Error here
btnRush should be Rushbtn
This is a example of cross browser event's I just made (not tested) )
var addEvent = function( element, type, callback, bubble ) { // 1
if(document.addEventListener) { // 2
return element.addEventListener( type, callback, bubble || false ); // 3
}
return element.attachEvent('on' + type, callback ); // 4
};
var onEvent = function( element, type, callback, bubble) { // 1
if(document.addEventListener) { // 2
document.addEventListener( type, function( event ){ // 3
if(event.target === element || event.target.id === element) { // 5
callback.apply(event.target, [event]); // 6
}
}, bubble || false);
} else {
document.attachEvent( 'on' + type, function( event ){ // 4
if(event.srcElement === element || event.srcElement.id === element) { // 5
callback.apply(event.target, [event]); // 6
}
});
}
};
Steps
Create a function that accepts 4 values ( self explaining )
Check if the browser supports addEventListener
Add event on the element
else add event on the element for older IE
Check that the (clicked) element is = to the passed element
call the callback function pass the element as this and pass the event
The onEvent is used for event delegation.
The addEvent is for your standard event.
here's how you can use them
The first 2 are for dynamically added elements
onEvent('rushBtn', 'click', function(){
alert('click')
});
var rush = document.getElementById('rushBtn');
onEvent(rush, 'click', function(){
alert('click');
});
// Standard Event
addEvent(rush, 'click', function(){
alert('click');
});
Event Delegation is this basically.
Add a click event to the document so the event will fire whenever & wherever then you check the element that was clicked on to see if it matches the element you need. this way it will always work.
Demo

Event capturing jQuery

I need to capture an event instead of letting it bubble. This is what I want:
<body>
<div>
</div>
</body>
From this sample code I have a click event bounded on the div and the body. I want the body event to be called first. How do I go about this?
Use event capturing instead:-
$("body").get(0).addEventListener("click", function(){}, true);
Check the last argument to "addEventListener" by default it is false and is in event bubbling mode. If set to true will work as capturing event.
For cross browser implementation.
var bodyEle = $("body").get(0);
if(bodyEle.addEventListener){
bodyEle.addEventListener("click", function(){}, true);
}else if(bodyEle.attachEvent){
document.attachEvent("onclick", function(){
var event = window.event;
});
}
IE8 and prior by default use event bubbling. So I attached the event on document instead of body, so you need to use event object to get the target object. For IE you need to be very tricky.
I'd do it like this:
$("body").click(function (event) {
// Do body action
var target = $(event.target);
if (target.is($("#myDiv"))) {
// Do div action
}
});
More generally than #pvnarula's answer:
var global_handler = function(name, handler) {
var bodyEle = $("body").get(0);
if(bodyEle.addEventListener) {
bodyEle.addEventListener(name, handler, true);
} else if(bodyEle.attachEvent) {
handler = function(){
var event = window.event;
handler(event)
};
document.attachEvent("on" + name, handler)
}
return handler
}
var global_handler_off = function(name, handler) {
var bodyEle = $("body").get(0);
if(bodyEle.removeEventListener) {
bodyEle.removeEventListener(name, handler, true);
} else if(bodyEle.detachEvent) {
document.detachEvent("on" + name, handler);
}
}
Then to use:
shield_handler = global_handler("click", function(ev) {
console.log("poof")
})
// disable
global_handler_off("click", shield_handler)
shield_handler = null;

Send a message when pressing Enter

Here is my code:
<input type=\"text\" id='MsgToSend" + ToClient + "t" + FromClient + "' onkeypress='ClientOnTyping();' />
where the FromClient and the ToClient are dynamically generated.
JavaScript:
function ClientOnTyping() {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
}
You need to attach an event listener on the element for keydown event.
var btn = document.getElementById('MsgToSend');
btn.addEventListerner('keydown', function (e) {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});
On traditional browsers, you can attach the event handler this way.
var btn = document.getElementById('MsgToSend');
btn.onkeydown = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;
if(keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});
In the scope of the handler function, e is an event object created automatically whenever an event fires in the DOM. You need to simply pass it to your handler.
For example:
<input ...onkeypress="ClientOnTyping(event);">
and
function ClientOnTyping(e) {
...
}
Also, consider using unobtrusive code instead of obtrusive. See Difference between obtrusive and unobtrusive javascript and Starx's answer.

is there an "onAnything" javascript event?

have dumb question.
Here I've got three events calling the same function, connected to the same <div>:
<html>
<head>
<script type='text/javascript'>
function universal_action_handler( event ) {
var eType = event.type;
var eTarget = event.target || event.srcElement;
console.log( "Captured Event, type=", eType, ", target=", eTarget );
if( 'mouseover' == eType ) {
console.info( "onMouseOver: set background color to red." );
eTarget.style.backgroundColor = 'red';
eTarget.style.fontSize = '';
}
if( 'mouseout' == eType ) {
console.info( "onMouseOut: set background color to transparent." );
eTarget.style.backgroundColor = 'transparent';
eTarget.style.fontSize = '';
}
if( 'click' == eType ) {
console.info( "click!" );
eTarget.style.fontSize = 'larger';
}
}
</script>
</head>
<body>
<div style='border: 1px dashed red; display: inline-block;'
onClick="universal_action_handler(event);"
onMouseOver="universal_action_handler(event);"
onMouseOut="universal_action_handler(event);">Click me!</div>
</body>
</html>
I have onClick='', onMouseOver='', and onMouseOut='', all connected to the same <div>, and all calling the same function. If I want to add an event, I have to add an onEventThingy='' and call the same universal action handler function above. Inside the function, it decides what kind of event (event.type) and takes action.
Is there an onAnything='' event that I can use to call the universal function for any event which may happen to that <div>?
Instead of all those onevent attributes (which should be avoided anyway), you could set the onevent properties on the DOM element like so:
div.onclick = div.onmouseover = div.onmouseout = universal_action_handler;
where div is a reference to your DIV element.
Btw this is how I would implement the handler:
function universal_action_handler ( e ) {
var target, style;
e = e || window.event;
target = e.target || e.srcElement;
style = target.style;
if ( e.type === 'click' ) {
style.fontSize = 'larger';
} else {
style.backgroundColor = e.type === 'mouseover' ? 'red' : 'transparent';
style.fontSize = '';
}
}
Live demo: http://jsfiddle.net/rPVUW/
No, there is no universal event.
You can try what Šime Vidas suggested, or some libraries (e.g., jQuery) allow you to bind multiple events to the same handler with a single line of code, but either way you do need to explicitly list out the events to be bound.
No, there's no way to attach the same handler to all possible events. Is that really what you want? This could lead to your handler containing a huge if..else block or big switch statement.
If you want to attach common functionality (logging in your example) to all event handlers, consider this JavaScript:
function logAndHandle(event, innerHandler) {
var eType = event.type;
var eTarget = event.target || event.srcElement;
console.log( "Captured Event, type=", eType, ", target=", eTarget );
return innerHandler(event);
}
Which you'd use like this:
<div onclick="logAndHandle(event, yourClickHandler);"
onmouseover="logAndHandle(event, yourMouseOverHandler);"
onmouseout="logAndHandle(event, yourMouseOutHandler)">Click me!</div>
Given that you seem to want some functionality to run for all events, and other functionality to be specific to particular events, I'd combine Jacob's answer with Šime Vidas's:
var log = function(innerHandler) {
return function(event){
var eType = event.type;
var eTarget = event.target || event.srcElement;
console.log( "Captured Event, type=", eType, ", target=", eTarget );
return innerHandler(event);
};
};
And use it thus:
div.onclick = log(yourClickHandler);
div.onmouseover = log(yourMouseOverHandler);
div.onmouseout = log(yourMouseOutHandler);
Currying the log function makes it very easy to compose future "all event" functionality:
var count = function(innerHandler){
var totalCount = 0;
return function(event){
totalCount += 1;
alert("I've been called " + totalCount + " times.");
return innerHandler(event);
};
};
div.onclick = count(log(yourClickHandler));
Anyway, if you want to do functional-style programming in Javascript, you'd also want to look at Function.apply and Function.call.
Using just javascript, no, there is no 'onAnything' attribute. If you have the ability to add jQuery, you can 'bind' multiple events to the same div and then run the same function.

Use onmousedown to get the ID of the element you just mousedowned on?

Is this possible?
I am attempting to write a function for onmousedown that will return the ID of the element you just clicked for later use in recreating that element in a different div.
You can use event delegation, to basically connect only one event handler to your entire document, and get the element which the event was originally dispatched, using event.target:
document.body.onmousedown = function (e) {
e = e || window.event;
var elementId = (e.target || e.srcElement).id;
// call your re-create function
recreate(elementId);
// ...
}
function recreate (id) {
// you can do the DOM manipulation here.
}
Edit: You can assign events to all your Scriptaculous draggables in this way:
Event.observe(window, 'load', function () {
Draggables.drags.each(function (item) {
Event.observe(item.element, 'mousedown', function () {
alert('mouseDown ' + this.id); // the this variable is the element
}); // which has been "mouse downed"
});
});
Check an example here.
CMS pretty much has the correct answer but you will need to make it a little more cross browser friendly.
document.body.onmousedown = function (e) {
// Get IE event object
e = e || window.event;
// Get target in W3C browsers & IE
var elementId = e.target ? e.target.id : e.srcElement.id;
// ...
}
Pls insert this code to your javascript.
document.getElementById("article").onmouseup(handMu);
If you want to replicate the div id, an easy way might be cloneNode like this:
<div id="node1">
<span>ChildNode</span>
<span>ChildNode</span>
</div>
<div id="container"></div>
<script type="text/javascript">
var node1 = document.getElementById('node1');
var node2 = node1.cloneNode(true);
node2.setAttribute('id', 'node2');
var container = document.getElementById('container');
container.appendChild(node2);
</script>

Categories

Resources