I want to do something before my page unloads so I'm trying to interrupt normal behaviour momentarily. I tried this but it doesn't seem to work:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `a`) {
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
return true; // return false = prevent default action and stop event propagation
}, 500);
}
}
0.5s is the time I need to display a short css animation before leaving the page.
You can try the following code:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `A`) { // !uppercased
e.preventDefault(); // prevent default anchor behavior
var goTo = element.href; // store target url
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
window.location = goTo; // navigate to destination
}, 500);
}
}
Related
I am using this code below to open all links on _blank pages and it works great!
I just have one problem.
How can I make it so a specific link or class is ignored by the script?
Here's the code:
<script>
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
window.open(element.href, "_blank", "location=yes");
return false; // prevent default action and stop event propagation
}
};
</script>
To ignore specific classes, use the below:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A' && !element.classList.contains('noBlank')) {
window.open(element.href, "_blank", "location=yes");
return false; // prevent default action and stop event propagation
}
};
<p>BBC should not be _blank</p>
Google
<br />
Yahoo
<br />
<a class="noBlank" href="http://www.bbc.co.uk">BBC</a>
I am making a TD element of table editable on double click:
$(document).on("dblclick", "#table>tbody>tr>td.cell", function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});
function stub(e) {
e.stopImmediatePropagation();
return false;
}
But when i double click on the text inside the editable div, the double click event propagates to the parent td causing undesired consequences. There are also other events (select, mousedown, etc) i want to prevent, so writing a stub for each of them doesn't look nice to me.
Is there a way to disable all currently active jQuery event handlers and enable them afterwards? Or somewhow stop propagating all events from the editable div to its parents?
Or somewhow stop propagating all events from the editable div to its parents?
It may not be very palatable, but it's not that bad to specifically disable the events:
$(this).on("select mousedown mouseup dblclick etc", false);
(Assuming this refers to the cell you're editing.)
There is a limited number of events, after all, and on allows you to list them in a space-delimited string and disable them by passing false.
You can then re-enable them by passing the same list and false again into off.
Use on / off JQuery methods :
var myFunction = function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
};
function stub(e) {
e.stopImmediatePropagation();
return false;
}
//Active the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
//Disable the events
$(document).off("dblclick", "#table>tbody>tr>td.cell",myFunction);
//Reactive the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
Update
You can also manage a variable set to true if the event must not be taking into account :
var skipEvent = true;
$(document).on("dblclick", "#table>tbody>tr>td.cell", function (e) {
//Check variable and skip if true
if (skipEvent)
return false;
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function () {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});
document.getElementById("but").onclick = showDropDown;
function showDropDown(e) {
document.getElementById("but").onclick = function() {};
if (e.stopPropagation) e.stopPropagation(); // W3C model
else e.cancelBubble = true; // IE model
document.getElementById("window").style.display = "inline-block";
document.onclick = function(e) {
var ele = document.elementFromPoint(e.clientX, e.clientY);
if (ele == document.getElementById("but")) {
hideDropDown();
return;
}
do {
if (ele == document.getElementById("window")) return;
} while (ele = ele.parentNode);
hideDropDown();
};
}
function hideDropDown() {
document.onclick = function() {};
document.getElementById("window").style.display = "none";
document.getElementById("but").onclick = showDropDown;
}
<input id="but" type="button" value="pressMe" />
<div id="window" style="display:none">popup</div>
Demo: http://jsfiddle.net/nazym/
I was trying to make the JavaScript code dynamic using variables instead of the specified elements' names but I could not. It always returns errors. I want to link it with different elements.
update
I want to replace the ids of the elements in the JavaScript code with variables so I can use it with any element.I tried to do it but failed. Basically, I want to use variables instead of the ids of the element and link it to the elements somehow again.
Use arguments instead:
function showDropDown(element, e) {
element.onclick = function() {};
// ....
hideDropDown(element);
}
And you would give the element it's onclick event handler like this:
document.getElementById('but').onclick = function(event) {
showDropDown(this, event);
};
Demo: http://jsfiddle.net/xNSZm/
Change the code to
var showDropdown = function(e) { ... };
document.getElementById("but").onclick = showDropDown;
In other words, store the function in a variable before assigning it.
In your code:
> document.onclick = function(e){
In browsers that support the IE event model, e will be undefined. To accommodate those browsers, you can use:
e = e || window.event;
To find the element that was clicked on, instead of:
> var ele = document.elementFromPoint(e.clientX, e.clientY);
you can do:
var ele = e.target || e.srcElement;
which will work in very many more browsers than elementFromPoint so should be more reliable and faster.
Hi I found this script online that adds an onChange event to an element and I would like to now add a second onChange event to the same element. Heres the script:
document.getElementById('piname').onchange =
function() {
removeChildren({
parentId: 'account_table',
childName: 'extraaccount'
});
}
And the onChange event i want to add is:
showAccount(this.value)
Use addEventListener() (and attachEvent as a fallback, if needed).
Example:
document.getElementById('piname').addEventListener("change", function(e){
e = e || event;
showAccount(e.target.value);
}, false);
Example, with fallback:
var element = document.getElementById('piname');
if(element.addEventListener){
element.addEventListener("change", function(e){
e = e || event;
showAccount(e.target.value);
}, false);
}
else if(element.attachEvent){
element.attachEvent("onchange", function(e){
e = e || event;
showAccount(e.target.value);
});
}
The simplest way is to cache the old function and call it from the new one:
var el = document.getElementById('piname'),
old = el.onchange;
el.onchange = function () {
old.call(el);
showAccount(this.value);
}
Other than that, you could use addEventListener (W3C standards) and attachEvent (IE8 and lower):
var el = document.getElementById('piname'),
fn = function (e) {
e = e || window.event;
showAccount((e.target || e.srcElement).value);
};
if ("addEventListener" in el) {
el.addEventListener("change", fn, false);
}
else {
el.attachEvent("onchange", fn);
}
Those methods allow you to attach as many handlers to events as you like.
I am trying to send the document and the control that the key was pressed in to the keypressed function.
Here is my code:
//Namespace
MyExt.BrowserOverlay = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", MyExt.BrowserOverlay.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget;
if (doc.location.href == "http://something.com"){
var txtBox = doc.getElementById('txtBox');
txtBox.addEventListener('keypress', keypressed, false); //Error Line
}
},
…
something like:
txtBox.addEventListener('keypress', keypressed(?,doc), false);
function keypressed(a,doc){
alert(a); //a relates to keypress
alert(doc.innerHTML);
}
Easiest way to pass variable is to attach it to Element that will trigger event, but you can access document by using global variable document.
As for event listeners, browsers handle events differently:
txtBox.someVar = "foobar"; // Any variable you want to pass
if(window.addEventListener){ // Firefox, Chrome...
txtBox.addEventListener('keypress', keypressed, false);
} else { // IE
txtBox.attachEvent('onkeypress', keypressed);
}
function keypressed(event){
// find event object
var e = event || window.event;
// find target object
var target = e.currentTarget;
if (e.target) target = e.target;
else if (e.srcElement) target = e.srcElement;
if (target.nodeType == 3) target = targ.parentNode;
// find key code
var code = e.charCode || e.keyCode;
alert(String.fromCharCode(code));
alert(target.someVar);
alert(document.body.innerHTML);
}
You can use gBrowser.contentDocument to get the document of the currently selected tab. See this article on the tabbed browser control for more info.