How to overwrite focus() in JavaScript for all elements? - javascript

I want to overwrite the function focus() for all HTML elements in JavaScript.
How do I do that?

The question asks for just how to override the .focus() method for HTML elements, so that will be answered first. There are however, other ways to trigger "focus" on elements, and overriding those methods are discussed below.
Please also note, it is probably not a good idea to override global prototypes.
Overriding the .focus() method on HTML elements
You can override the focus function for all HTMLElement's by modifying its prototype.
HTMLElement.prototype.focus = function () {
// ... do your custom stuff here
}
If you still want to run the default focus behavior and run your custom override, you can do the following:
let oldHTMLFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function () {
// your custom code
oldHTMLFocus.apply(this, arguments);
};
Overriding the focus event set via handlers on HTML elements
This is done in a similar fashion to overriding the .focus() method. However, in this case, we will target the EventTarget constructor and modify the addEventListener prototype:
let oldAddListener = HTMLElement.prototype.addEventListener;
EventTarget.prototype.addEventListener = function () {
let scope = this;
let func = arguments[1];
if (arguments[0] === 'focus') {
arguments[1] = function (e) {
yourCustomFunction(scope);
func(e);
};
}
oldAddListener.apply(this, arguments);
};
If you don't want original behavior at all, you can remove the func call (func(e)).
Overriding the focus event set via the onfocus attribute
Doing this is actually quite tricky, and will most likely have some unforseen limitations. That said, I could not find a way to override this by modifying prototypes, etc. The only way I could get this work was by using MutationObservers. It works by finding all elements that have the attribute onfocus and it sets the first function to run to your override function:
let observer = new MutationObserver(handleOnFocusElements);
let observerConfig = {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ['onfocus']
};
let targetNode = document.body;
observer.observe(targetNode, observerConfig);
function handleOnFocusElements() {
Array
.from(document.querySelectorAll('[onfocus]:not([onfocus*="yourCustomFunction"])'))
.forEach(element => {
let currentCallbacks = element.getAttribute('onfocus');
element.setAttribute('onfocus', `yourCustomFunction(this); return; ${currentCallbacks}`);
});
}
If you want to stop the original onfocus from firing its events completely, you can just empty the onfocus attribute entirely on any mutation changes, and just set the value to your desired function.
An example with all of the code snippets together:
(function() {
window.yourCustomFunction = function(target) {
console.log('OVERRIDE on element', target);
};
let observer = new MutationObserver(handleOnFocusElements);
let observerConfig = {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ['onfocus']
};
let targetNode = document.body;
// Start overriding methods
// The HTML `.focus()` method
let oldHTMLFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function() {
yourCustomFunction(this);
oldHTMLFocus.apply(this, arguments);
};
// Event Target's .addEventListener prototype
let oldAddListener = HTMLElement.prototype.addEventListener;
EventTarget.prototype.addEventListener = function() {
let scope = this;
let func = arguments[1];
if (arguments[0] === 'focus') {
arguments[1] = function(e) {
yourCustomFunction(scope);
func(e);
};
}
oldAddListener.apply(this, arguments);
};
// Handle the onfocus attributes
function handleOnFocusElements() {
Array
.from(document.querySelectorAll('[onfocus]:not([onfocus*="yourCustomFunction"])'))
.forEach(element => {
let currentCallbacks = element.getAttribute('onfocus');
element.setAttribute('onfocus', `yourCustomFunction(this); return; ${currentCallbacks}`);
});
}
window.addEventListener('load', () => {
handleOnFocusElements();
observer.observe(targetNode, observerConfig);
});
})();
let input = document.querySelector('input');
input.addEventListener('focus', function() {
console.log('Add Event Listener Focus');
});
function attributeHandler() {
console.log('Called From the Attribute Handler');
}
<input type="text" onfocus="attributeHandler()">

In pure JS:
HTML:
<input id="test" type="textfield" />​
JS:
var myInput = document.getElementById("test");
myInput.addEventListener("focus",deFocus(myInput),true);
function deFocus(element) {
element.setAttribute('readonly','readonly');
return false;
}
Working fiddle
In JQuery:
HTML
​<input id="test" type="textfield" />
JQuery
​$('#test').focus(function() {
$(this).blur();
});​​​​​​​​​​​​​​​​​​​​
Working fiddle
You can add the EventListener to whatever you want, class, id, etc. and run it through the function or trigger something else to unlock them. JQuery can also handle this pretty smoothly, though if you're going that route I would suggest using a class as a selector and then you can add and remove the class dynamically to disable focus.

Related

.js alert(); when text in span change

I got this Code:
const odleglosc = parseFloat(document.getElementsByClassName("dystans")[0].innerText);
const daleko = "za daleko";
if (odleglosc > 200) {
alert(daleko);
}
<span data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans">500</span>
It runs fine, because at starting point there is number higher than 200 in it.
But when i change it, alert don't trigger again..
How can i solve that? :(
Im not sure about how the span value will change, so this example works with an input. The same idea could also be applied to a span tho.
<input onchange="theFunction()" data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans" value="500"></input>
<script>
function theFunction() {
var odleglosc = parseFloat(document.getElementsByClassName("dystans")[0].value);
var daleko = "za daleko";
if (odleglosc > 200)
{
alert(daleko);
}
}
</script>
Here, onChange calls the function whenever the value in the input field changes.
Do You want to show alert after each change of the value? If yes, use event listener for input (not for span).
Update:
Use MutationObserver for this case.
let span = document.getElementById('dystans');
function updateValue(value) {
var daleko = "za daleko";
if (parseFloat(value) > 200)
{
alert(daleko);
}
}
// create a new instance of 'MutationObserver' named 'observer',
// passing it a callback function
observer = new MutationObserver(function(mutationsList, observer) {
let value = mutationsList.filter(x => x.target.id =='dystans')[0].target.innerHTML;
updateValue(value);
});
// call 'observe' on that MutationObserver instance,
// passing it the element to observe, and the options object
observer.observe(span, {characterData: true, childList: true, attributes: true});
span.innerHTML = '3000';
<span data-pafe-form-builder-live-preview="lechnarlok" class="dystans" id="dystans">500</span>
Source:
Detect changes in the DOM
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Adding or removing a class to an element dynamically using Mutation Observer

I want to remove a class from an element when a modal pops-up But when I searched online I found DOMNodeInserted and it was working until it went live and the error I got was DOMNodeInserted has been deprecated. The error I keep getting below
enter image description here
CODE WORKING BELOW, but has been deprecated.
$(document).on('DOMNodeInserted', function(e) {
if ( $("body").hasClass('modal-open') ) {
$(".hide-search").hide();
// $(".nav-menu").addClass("border-0");
} else if ($("body").hasClass('modal-open') === false){
$(".hide-search").show();
// $(".nav-menu").removeClass("border-0");
}
});
New code i wanted to Implement but i don't know how to go about it.
let body = document.querySelector('body');
let observer = new MutationObserver(mutationRecords => {
console.log(mutationRecords); // console.log(the changes)
// observe everything except attributes
observer.observe(body, {
childList: true, // observe direct children
subtree: true, // and lower descendants too
characterDataOldValue: true // pass old data to callback
});
});
}
}
observe() should be outside the callback
all you need to observe is the class attribute, nothing else, so there's no need for the extremely expensive subtree:true.
the class may include something else so you need to ignore irrelevant changes
new MutationObserver((mutations, observer) => {
const oldState = mutations[0].oldValue.split(/\s+/).includes('modal-open');
const newState = document.body.classList.contains('modal-open');
if (oldState === newState) return;
if (newState) {
$('.hide-search').hide();
} else {
$('.hide-search').show();
}
}).observe(document.body, {
attributes: true,
attributeFilter: ['class'],
attributeOldValue: true,
});
I was able to resolve the above problem with this solution
function myFunction(x) {
if (x.matches) {
var body = $("body");
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === "class") {
var attributeValue = $(mutation.target).prop(mutation.attributeName);
console.log("Class attribute changed to:", attributeValue);
if(attributeValue == "ng-scope modal-open") {
$(".input-group").addClass("removeDisplay");
$(".nav-menu").addClass("hide-nav-menu");
} else {
$(".input-group").removeClass("removeDisplay");
$(".nav-menu").removeClass("hide-nav-menu");
}
}
});
});
observer.observe(body[0], {
attributes: true
});
}
}
// Wow It's working.
var x = window.matchMedia("(max-width: 1240px)")
myFunction(x)
x.addListener(myFunction)
Firstly I used a match media to check if the screen is lesser than 1240px size then I used the mutation along with checking if an attribute class is present, then perform some certain actions based on that.

MutationObserver for when parent changes

Is there a way to detect when the parent of an element changes (namely when changing from null to !null -- i.e., when the element is initially added to the DOM) using a MutationObserver? I can't find any documentation that shows how this could be achieved.
I am programmatically creating elements with document.createElement(). I return the created element from a function, but want to create a listener from within the function to react when the element is eventually added to the DOM, without knowing where or which parent it will be added to.
I'm not quite sure how else to phrase this, honestly.
const elem = document.createElement('div');
let added = false;
elem.addEventListener('added-to-dom', () => { added = true; });
// ^ how do I achieve this?
assert(added == false);
document.body.addChild(elem);
assert(added == true);
I don't see what's so hard about understanding this or why it was closed.
An easy but inelegant way is to monkeypatch Node.prototype.appendChild (and, if necessary, Element.prototype.append, Element.prototype.insertAdjacentElement, and Node.prototype.insertBefore) to watch for when an element is added to the DOM:
const elementsToWatch = new Set();
const { appendChild } = Node.prototype;
Node.prototype.appendChild = function(childToAppend) {
if (elementsToWatch.has(childToAppend)) {
console.log('Watched child appended!');
elementsToWatch.delete(childToAppend);
}
return appendChild.call(this, childToAppend);
};
button.addEventListener('click', () => {
console.log('Element created...');
const div = document.createElement('div');
elementsToWatch.add(div);
setTimeout(() => {
console.log('About to append element...');
container.appendChild(div);
}, 1000);
});
<button id="button">Append something after 1000ms</button>
<div id="container"></div>
Mutating built-in prototypes generally isn't a good idea, though.
Another option would be to use a MutationObserver for the whole document, but this may well result in lots of activated callbacks for a large page with frequent mutations, which may not be desirable:
const elementsToWatch = [];
new MutationObserver(() => {
// instead of the below, another option is to iterate over elements
// observed by the MutationObserver
// which could be more efficient, depending on how often
// other elements are added to the page
const root = document.documentElement; // returns the <html> element
const indexOfElementThatWasJustAdded = elementsToWatch.findIndex(
elm => root.contains(elm)
);
// instead of the above, could also use `elm.isConnected()` on newer browsers
// if an appended node, if it has a parent,
// will always be in the DOM,
// instead of `root.contains(elm)`, can use `elm.parentElement`
if (indexOfElementThatWasJustAdded === -1) {
return;
}
elementsToWatch.splice(indexOfElementThatWasJustAdded, 1);
console.log('Observed an appended element!');
}).observe(document.body, { childList: true, subtree: true });
button.addEventListener('click', () => {
console.log('Element created...');
const div = document.createElement('div');
div.textContent = 'foo';
elementsToWatch.push(div);
setTimeout(() => {
console.log('About to append element...');
container.appendChild(div);
}, 1000);
});
<button id="button">Append something after 1000ms</button>
<div id="container"></div>
You could listen for the DOMNodeInserted-event and compare the elements id.
Notice: This event is marked as Depricated and will probably stop working in modern modern browsers at some point in the near
future.
let container = document.getElementById('container');
let button = document.getElementById('button');
document.body.addEventListener('DOMNodeInserted', function(event) {
if (event.originalTarget.id == button.id) {
console.log('Parent changed to: ' + event.originalTarget.parentElement.id);
}
});
button.addEventListener('click', function(event) {
container.appendChild(button);
});
#container {
width: 140px;
height: 24px;
margin: 10px;
border: 2px dashed #c0a;
}
<div id="container"></div>
<button id="button">append to container</button>

Using bind function in event listeners

I have been writing a plugin, and i really like this format
Function.prototype._onClick = function() {
// do something
}
Fuction.prototype.addListner = function() {
this.$element.on('click', this._onClick.bind(this));
}
the problem is sometimes i need the element being clicked and the main object. Doing as below i loose the dom element and not using bind looses the main object.
Fuction.prototype.addListner {
this.$element.find('.some-class').on('click', this._onClick.bind(this));
}
To achieve that i go back to ugly version
Fuction.prototype.addListner = function() {
var self = this;
this.$element.find('.some-class').on('click', function() {
self._onClick($(this));
});
}
Is there any better way to do this?
As zerkms, you can use the event.target to achieve what you want.
When using .on, the handler is :
handler
Type: Function( Event eventObject [, Anything extraParameter ] [, ...
] ) A function to execute when the event is triggered. The value false
is also allowed as a shorthand for a function that simply does return
false.
So your _onClick function will receive click event as its 1st parameter, then from event.target, you can now get the clicked item.
var Test = function(sel) {
this.$element = $(sel);
this.value = 'My value is ' + this.$element.data('val');
};
Test.prototype.addListner = function() {
this.$element.find('.some-class').on('click', this._onClick.bind(this));
}
Test.prototype._onClick = function(evt) {
// Get the target which is being clicked.
var $taget = $(evt.target);
//
console.log(this.value);
// use $target to get the clicke item.
console.log($taget.data('val'));
}
var test = new Test('#test');
test.addListner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="test" data-val="divVal">
<button class="some-class" data-val="Button-A">btnA</button>
<button class="some-class" data-val="Button-B">btnB</button>
</div>

WinJS Custom Control Events "invalid argument"

I'm creating a custom WinJS control with an event listener. For simplicity, this example should fire an event whenever it is tapped.
This is created with the markup:
<div class="alphaNavBar" data-win-control="MobMan.Controls.AlphaNavBar"></div>
The control is implemented here. It throws an "invalid argument" exception at the dispatchEvent(...) line.
(function () {
var alphaNavBar = WinJS.Class.define(function (el, options) {
// Create control
var self = this;
this._element = el || document.createElement("div");
this._element.winControl = this;
this._element.innerText = "Hello World!";
this._selection = false;
// Listen for tap
this._element.addEventListener("MSPointerDown", function (evt) {
// Toggle selection
self._selection = !self._selection;
// Selection changed, fire event
// Invalid argument here
self._element.dispatchEvent("mySelectionChanged", { selection: self._selection });
// Invalid argument here
});
});
// Add to global namespace
WinJS.Namespace.define("MobMan.Controls", {
AlphaNavBar: alphaNavBar
});
// Mixin event properties
WinJS.Class.mix(MobMan.Controls.AlphaNavBar, WinJS.Utilities.createEventProperties("mySelectionChanged"), WinJS.UI.DOMEventMixin);
})();
This event is listened to by:
var alphaNavBar = document.querySelector(".alphaNavBar");
alphaNavBar.addEventListener("mySelectionChanged", function (evt) {
// Should fire when alphaNavBar is tapped
debugger;
});
What am I doing wrong here?
I posted my question here as well and got an answer modifying the event dispatch like so:
// Listen for tap
this._element.addEventListener("MSPointerDown", function (evt) {
// Toggle selection
this._selection = !this._selection;
// Create the event.
var _event = document.createEvent('customevent');
// Define that the event name is 'mySelectionChanged' and pass details.
_event.initCustomEvent('mySelectionChanged', true, true, { selection: this._selection });
// Selection changed, fire event
this.dispatchEvent(_event);
});
This was able to trigger the event correctly for me. Still not sure what I was doing wrong before, but it is fixed now.

Categories