Vanilla JS version of jQuery document on click for links? - javascript

Is there a pure JS version of this?
$(document).on('click', 'a[href]', function(event) {
event.preventDefault();
here.change(this);
});
The specific feature I'm looking for is adding event listeners for any link that's created later via JS (AJAX for example).

Modern browsers support matches which makes this a lot easier
document.addEventListener('click', function(event) {
if (event.target.matches('a[href], a[href] *')) {
event.preventDefault();
console.log('works fine')
}
}, false);
document.body.innerHTML = '<span>Click Me!</span><br /><div>not me!</div>';
You could make this more convenient with a simple function
function addEvent(parent, evt, selector, handler) {
parent.addEventListener(evt, function(event) {
if (event.target.matches(selector + ', ' + selector + ' *')) {
handler.apply(event.target.closest(selector), arguments);
}
}, false);
}
Note that closest() is only supported in the latest browsers, there's a polyfill on MDN
This replicates the jQuery behaviour a lot more, and is easier to use, it also sets the value of this correctly
function addEvent(parent, evt, selector, handler) {
parent.addEventListener(evt, function(event) {
if (event.target.matches(selector + ', ' + selector + ' *')) {
handler.apply(event.target.closest(selector), arguments);
}
}, false);
}
/* To be used as */
addEvent(document, 'click', 'a[href]', function(e) {
console.log(this)
});
/* Add a dynamic element */
document.body.innerHTML = '<span>Click Me!</span><br /><div>not me!</div>';

You can attach click event to document. check if event.target .tagName is "A" and if event.target has property .href. It is not clear what expected result of here.change(this) is expected to do from text of Question
function dynamicA() {
var a = document.createElement("a");
a.href = "";
a.textContent = "a";
document.body.innerHTML += "<br>";
document.body.appendChild(a);
}
document.addEventListener("click", function(event) {
event.preventDefault();
if (event.target.tagName === "A" && event.target.href) {
// do stuff
dynamicA();
}
});
<a href>a</a>

I believe this accomplishes what you want:
// for all dom elements on click
document.onclick = function(event) {
var el = event.target; // get what is being clicked on
if(el.hasAttribute('href') && el.tagName == 'a') { // check if it's a link
event.preventDefault();
here.change(this); // what is this?
}
}

Related

Event Delegation / Attaching events to dynamically created elements using Vanilla JavaScript

I am in the process of converting a large script from jQuery to JavaScript. This was code that I didn't write myself but that I forked from a project on GitHub.
I've consulted W3Schools, the official documentation and this website as a reference.
http://youmightnotneedjquery.com/
One of the parts I'm trying to convert into JavaScript is the following.
$('body').on('click','.vb',function(){
exportVB(this.value);
});
According to the aforementioned link,
$(document).on(eventName, elementSelector, handler);
converts to this
document.addEventListener(eventName, function(e) {
// loop parent nodes from the target to the delegation node
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches(elementSelector)) {
handler.call(target, e);
break;
}
}
}, false);
My attempt is as follows
/*document.addEventListener('click',function(e) {
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches('.vb')) {
exportVB.call(target,e);
break;
}
}
}, false);*/
That evidently didn't work so I did a Google search that brought me to this StackOverflow solution
Attach event to dynamic elements in javascript
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
//$(document).on('click','#btnPrepend',function(){//do something})
Testing that gave me this idea. I commented it out because that apparently didn't work either.
/*document.addEventListener('click',function(e) {
if (e.target && e.target.className == 'vb') {
exportVB(this.value);
}
});*/
Just for reference, the original jQuery function works well.
I solved it.
document.body.addEventListener('click',function(e) {
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches('.vb')) {
exportVB(target.value);
break;
}
}
});
I can't explain how it worked because I didn't write the original code in the first place. But there were two things I change.
exportVB.call(target.e) to exportVB(target.value)
Removing the false as the last argument.
Rather than iterating over each parent element manually, consider using .closest instead, which will return the ancestor element (or the current element) which matches a selector:
document.querySelector('button').addEventListener('click', () => {
document.body.insertAdjacentHTML('beforeend', '<span class="vb">some span </span>');
});
document.body.addEventListener('click', (e) => {
if (e.target.closest('.vb')) {
console.log('vb clicked');
}
});
<button>add span</button>

What does colon mean in jQuery when used inside of .trigger?

I looked at http://api.jquery.com/trigger/ and the examples did not answer my question. I am looking at some code and would like to know what this block of code is doing.
$(document).on('click', '#SubmitQuery', function(event) {
event.preventDefault();
$(document).trigger('filter:submit');
});
Specifically, what does the colon inside of that trigger function do? For complete context, here is what filter is (I assume that the 'filter' inside of the trigger function refers to that filter object):
var filter = {
init: function() {
$(document).on('keypress', '#Filter', debounce(function(event) {
if (event.keyCode == 13) {
$(document).trigger('filter:text');
}
}, 300));
$(document).on('click', '#ClearFilter', function(event) {
event.preventDefault();
$('#FilterText').val('');
$('#FilterText').focus();
$(document).trigger('filter:clear');
});
$(document).on('change', '.filterSection [type=checkbox]', function(event) {
var group = $(this).parents('[data-filter-group]').attr('data-filter-group');
var $checkboxes = $('[data-filter-group=' + group + '] [type=checkbox]');
if ($checkboxes.length > 0) {
if ($checkboxes.filter(':checked').length === 0) {
$(this).prop('checked', true);
}
}
});
$(document).on('click', '#SubmitQuery', function(event) {
event.preventDefault();
$(document).trigger('filter:submit');
});
$("#Filter").focus();
}
};
The colons specifies custom events, essentially creating namespaces for events you can call later without overriding default events or having to create multiple listeners on the same event.
You can find more information here: https://learn.jquery.com/events/introduction-to-custom-events/

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

detect click on link in Firefox

I want to detect in my firefox extension if a link has been clicked. So far, for this I add a click event listener to the window
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
handleWindowClick : function(event) {
if ("event.target is a link") {
// do something
}
};
For some links the event.target is simple the URL. However, for some links I get, e.g., a HTMLSpanElement as event.target. Am I on the right track to catch link clicks or are there other ways? If it works this way, how can I ensure the successfully test if the event.targer is a link?
You're adding an event listener to the main window which registers any click. The url's you're having problems with must be wrapped in a <span> tag. What you need is event delegation
Why don't you just put the click event listener to anchors (<a>)?
var hrefs = document.getElementsByTagName('a');
for (i = 0; i < hrefs.length; i++) {
hrefs[i].addEventListener(...)
...
}
or in jQuery:
$('a').click(function () {
...
});
check this out, i hope this is what you are looking for.
window.addEventListener("click", function(event) {
handleWindowClick(event);
}, false);
function handleWindowClick(event){
var origEl = event.target || event.srcElement;
if(origEl.tagName === 'A')
alert("anchor link is clicked");
else if(origEl.parentNode.tagName === 'A')
alert("clicked inside anchor");
else if(origEl.tagName === 'SPAN')
alert("span is clicked");
}
fiddle : http://jsfiddle.net/5zXkN/3/
I extended the answer of dku.rajkumar to support arbitrary constructs within "A"-tags. I'm simply go up the tree until I either find an "A" or I'm at the root (so no link clicked in this case). It seems to do the trick. Thanks to all for your help!
window.addEventListener("click", function(event) { handleWindowClick(event); }, false);
...
isLink : function(element) {
if(element.tagName === 'A')
return true;
else
if (element.parentNode)
return this.isLink(element.parentNode)
else
return false;
},
handleWindowClick : function(event) {
var element = event.target || event.srcElement;
var isLink = this.isLink(element);
if (isLink)
dump("A link has been clicked.\n");
},

Simulating "focus" and "blur" in jQuery .live() method

Update: As of jQuery 1.4, $.live() now supports focusin and focusout events.
jQuery currently1 doesn't support "blur" or "focus" as arguments for the $.live() method. What type of work-around could I implement to achieve the following:
$("textarea")
.live("focus", function() { foo = "bar"; })
.live("blur", function() { foo = "fizz"; });
1. 07/29/2009, version 1.3.2
Working solution:
(function(){
var special = jQuery.event.special,
uid1 = 'D' + (+new Date()),
uid2 = 'D' + (+new Date() + 1);
jQuery.event.special.focus = {
setup: function() {
var _self = this,
handler = function(e) {
e = jQuery.event.fix(e);
e.type = 'focus';
if (_self === document) {
jQuery.event.handle.call(_self, e);
}
};
jQuery(this).data(uid1, handler);
if (_self === document) {
/* Must be live() */
if (_self.addEventListener) {
_self.addEventListener('focus', handler, true);
} else {
_self.attachEvent('onfocusin', handler);
}
} else {
return false;
}
},
teardown: function() {
var handler = jQuery(this).data(uid1);
if (this === document) {
if (this.removeEventListener) {
this.removeEventListener('focus', handler, true);
} else {
this.detachEvent('onfocusin', handler);
}
}
}
};
jQuery.event.special.blur = {
setup: function() {
var _self = this,
handler = function(e) {
e = jQuery.event.fix(e);
e.type = 'blur';
if (_self === document) {
jQuery.event.handle.call(_self, e);
}
};
jQuery(this).data(uid2, handler);
if (_self === document) {
/* Must be live() */
if (_self.addEventListener) {
_self.addEventListener('blur', handler, true);
} else {
_self.attachEvent('onfocusout', handler);
}
} else {
return false;
}
},
teardown: function() {
var handler = jQuery(this).data(uid2);
if (this === document) {
if (this.removeEventListener) {
this.removeEventListener('blur', handler, true);
} else {
this.detachEvent('onfocusout', handler);
}
}
}
};
})();
Tested in IE/FF/Chrome. Should work exactly as you intended.
UPDATE: Teardowns now work.
This functionality is now included in jQuery core (as of 1.4.1).
live() is jQuery's shortcut to event delegation. To answer your question, see Delegating the focus and blur events.
It's pretty ingenious: for standards compliant browsers he uses event capturing to trap those events. For IE he uses IE's proprietary focusin (for focus) and focusout (for blur) events, which do bubble, allowing traditional event delegation.
I'll leave the porting of it to jQuery as an exercise.
they have been added on jquery 1.4.1 ... now .live() function supports fucus and blur events =) Greetings
Looks like the problem is when checking the event.type it returns "focusin" & "focusout"
$('input').live("focus blur", function(event){
if (event.type == "focusin") {
console.log(event.type);
}else{
console.log(event.type);
}
});
one more addition: this solution does not support more than one parameter.
i tried:
$(el).live("focus blur", function(e) {
if (e.type == "focus") {
etc.
and it only fired the blur event.
nevertheless this solution has been helpful.

Categories

Resources