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
Related
if I'm fetching multiple events using jquery how can I determine which event is currently triggered so I can processed further, for example
$("#someId").on('paste blur', function (e) {
var data = '';
// if paste
data = e.originalEvent.clipboardData.getData('text')
// if blur
data = $("#someId").val();
});
You can use event.type to get the current event,
$("#someId").on('paste blur', function (e) {
if ('paste' == e.type) {
data = e.originalEvent.clipboardData.getData('text')
} else if ('blur' == e.type) {
data = $("#someId").val();
}
});
You can use Event.type.
$("#someId").on('paste blur', function (e) {
var data = '';
if(e.type == 'paste') {
data = e.originalEvent.clipboardData.getData('text')
}
if(e.type == 'blur') {
data = $("#someId").val();
}
});
You might wish to consider registering separate handlers depending on how different you're going to handle the events though.
To avoid unnecessary if conditions you can add only the events you actually needs:
// Bind up a couple of event handlers
$("#txt").on({
click: function() {
console.log("click")
},
mouseout: function() {
console.log("mouseout")
},
change: function() {
console.log("change")
}
});
//Lookup events for this particular Element
//prints out an object with all events on that element
console.log($._data($("#txt")[0], "events"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt" />
As somebody who (unfortunately) learned more of jQuery than raw javascript I am just now taking the time to replace all of my code with raw javascript. No, it's not needed, but it's an easier way for me to learn. A problem I am facing is converting all of my $(document).on with raw javascript. My website is a "single-page application" and most of my actual HTML is in different files which are called via Ajax requests. So, my question is, how would I look for an event fired from dynamically loaded content? I am assuming I would have to add an onclick event to them, but how is it that jQuery does it without needing an onclick event?
Binding handlers in native API is done using addEventListener().
To emulate jQuery's event delegation, you could fairly easily create a system that uses the .matches() method to test the selector you give.
function delegate(el, evt, sel, handler) {
el.addEventListener(evt, function(event) {
var t = event.target;
while (t && t !== this) {
if (t.matches(sel)) {
handler.call(t, event);
}
t = t.parentNode;
}
});
}
There are probably some tweaks to be made, but basically it's a function that takes the element to bind to, like document, the event type, a selector and the handler.
It starts on the e.target and traverses up the parents until it gets to the bound element. Each time, it checks to see if the current element matches the selector, and if so, it invokes the handler.
So you'd call it like this:
delegate(document, "click", ".some_elem", function(event) {
this.style.border = "2px dashed orange";
});
Here's a live demo that also adds dynamic elements to show that new elements are picked up as well.
function delegate(el, evt, sel, handler) {
el.addEventListener(evt, function(event) {
var t = event.target;
while (t && t !== this) {
if (t.matches(sel)) {
handler.call(t, event);
}
t = t.parentNode;
}
});
}
delegate(document, "click", ".some_elem", function(event) {
this.parentNode.appendChild(this.cloneNode(true));
this.style.border = "2px dashed orange";
});
<div>
<p class="some_elem">
<span>
CLICK ME
</span>
</p>
</div>
Here's a shim to add a bit more support for .matches().
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.webkitMatchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
Here is a javascript equivalent to on()
jQuery
$(document).on('click', '#my-id', callback);
function callback(){
...handler code here
}
Javascript
document.addEventListener('click', function(event) {
if (event.target.id == 'my-id') {
callback();
}
});
function callback(){
...handler code here
}
With this approach, the idea is to make use of event.target. Of course, as the selector changes, your code will have to get more involved
In modern browsers, you can use Element.closest() to simplify replication of jQuery's .on() method as well as ensure that you capture event bubbling from children of the targeted element (a nuance that some other implementations overlook). Older browsers, including IE, would require a polyfill for this to work.
const on = (element, type, selector, handler) => {
element.addEventListener(type, (event) => {
if (event.target.closest(selector)) {
handler(event);
}
});
};
on(document, 'click', '#test', (event) => console.log('click'));
<button id="test">
Clickable
<i>Also Clickable</i>
</button>
Another approach for modern browsers would be something like this:
const on = (selector, event, handler, element=document) => {
element.addEventListener(event, (e) => { if(e.target.matches(selector)) handler(e); });
};
// click will work for each selector
on('[type="button"], .test, #test','click', e => {
alert(e.target.innerHTML);
});
// click event will work for nested .test3 element only
on('.test3','click', e => {
alert(e.target.innerHTML);
},document.querySelector('.test2'));
<div id="test">
test
</div>
<div class="test">
test 1
</div>
<div class="test">
test 2
</div>
<button type="button">
go
</button>
<div class="test3">
test 3 outer
</div>
<div class="test2">
<div class="test3">
test 3 inner
</div>
test 2
</div>
I would offer a very small improvement over the fantastic accepted answer:
function add_event(el, name, callback, selector) {
if (selector === undefined) {
el.addEventListener(name, callback);
}
else {
el.addEventListener(name, function(event) {
var t = event.target;
while (t && t !== this) {
if (t.matches(selector)) {
callback.call(t, event);
}
t = t.parentNode;
}
});
}
}
By switching the last 2 parameters around, you can recover the default addEventListener behavior when you leave out the selector.
I want to add and suggest a simple jQuery like on method:
It's similar to #benvc answer with an improvement which is binding the handler to this pointing to the attached element.
The solution uses Element.closest which is widely supported. If you want to support older browsers you can add a polyfill
//The on() function:
const on = (ele, type, selector, handler) => {
ele.addEventListener(type, (event) => {
let el = event.target.closest(selector);
if (el) handler.call(el, event); //The element is bind to this
});
};
//Example:
on(document, 'click', '.any-selector', function(event) {
console.log(this, event.target);
// this -> The .any-selector element.
// event.target -> The firing element a descendent of any-selector
});
I want to apply a click event to an entire page in Javascript, to everything but a single banner on top. Let's say that the banner that I don't want the event in has an id of 'bannerID'. I tried doing the following:
document.onclick = function(){clickEvent()}
document.getElementById("bannerID").onclick = function(){return false;}
However, it looks like the document event overrides everything. Does anyone have any advice?
Check for the element-id within the handler, something like;
document.onclick = clickEvent;
function clickEvent(e) {
var from = e.target || e.srcElement;
if (from.id === 'bannerID') { return; }
/* ... the handling continues ... */
}
This is called event delegation
Pass in an event parameter to the callback and check if the id is 'bannerID'
document.onclick =
function(event){
if(event.target.id != 'bannerID'){
clickEvent()
}
};
demo
In the code you have above, you are adding two click events to "bannerID" - so it will execute clickEvent() and return false.
You can, however, exclude the specific element from the onclick function. This might help:
document.onclick = function(e) {
if (e.target.id === 'bannerID') {
return false;
} else {
clickEvent();
}
};
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;
This question already has answers here:
How can I check if a key is pressed during the click event with jQuery?
(5 answers)
Closed 5 years ago.
I need to know if the user is clicking or CONTROL CLICKING a div element.
I have seen examples on how to do it using event listeners.. but my code is already set in place, and is using an on-element onclick method..
HTML
<div id='1' onclick='selectMe()'>blah</div>
JS
function selectMe(){
//determine if this is a single click, or a cntrol click
}
...also would love to know if it was a left or right mouse button click.
In your handler, check the window.event object for the property ctrlKey as such:
function selectMe(){
if (window.event.ctrlKey) {
//ctrl was held down during the click
}
}
UPDATE:
the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:
HTML
<span onclick="handler(event)">Click me</span>
JS
function handler(ev) {
console.log('CTRL pressed during click:', ev.ctrlKey);
}
The same applies for keyboard events
See also
KeyboardEvent.getModifierState()
2021 UPDATE: There are better ways to do this now. Please be sure to check out the other answers
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey.
Look down for example
$("xyz").click(function(e)){
if(e.ctrlKey){
//if ctrl key is pressed
}
else{
// if ctrl key is not pressed
}
}
note: https://www.w3schools.com/jsref/event_key_keycode.asp
Try this code,
$('#1').on('mousedown',function(e) {
if (e.button==0 && e.ctrlKey) {
alert('is Left Click');
} else if (e.button==2 && e.ctrlKey){
alert('is Right Click');
}
});
Sorry I added e.ctrlKey.
Try this:
var control = false;
$(document).on('keyup keydown', function(e) {
control = e.ctrlKey;
});
$('div#1').on('click', function() {
if (control) {
// control-click
} else {
// single-click
}
});
And the right-click triggers a contextmenu event, so:
$('div#1').on('contextmenu', function() {
// right-click handler
})
You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.
From above only , just edited so it works right away
<script>
var control = false;
$(document).on('keyup keydown', function (e) {
control = e.ctrlKey;
});
$(function () {
$('#1x').on('click', function () {
if (control) {
// control-click
alert("Control+Click");
} else {
// single-click
alert("Single Click");
}
});
});
</script>
<p id="1x">Click me</p>
pure javascript:
var ctrlKeyCode = 17;
var cntrlIsPressed = false;
document.addEventListener('keydown', function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
document.addEventListener('keyup', function(){
if(event.which=="17")
cntrlIsPressed = true;
});
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}