Reputation: 635
I have a javascript to ask the user to confirm that they want to leave my website. This is how it looks:
function confirmLeave()
{
if(confirm("Do you want to leave my webpage?")) {
return true;
} else {
if(window.event) {
window.event.returnValue = false;
} else {
e.preventDefault();
}
return false;
}
}
function initiate ()
{
var links = document.getElementsByClassName("external-link");
for (var i = 0; i < links.length; i++) {
links[i].onclick = confirmLeave;
}
}
window.onload = initiate;
It works good in Firefox and Chrome but not in IE8. I know that document.getElementsByClassName
doesn't work and I tried to remake my code using document.getElementsbyTakeName
but haven't got it to work. This is what I came up with:
function confirmLeave()
{
if(confirm("Do you want to leave my webpage?")) {
return true;
} else {
if(window.event) {
window.event.returnValue = false;
} else {
e.preventDefault();
}
return false;
}
}
funciton initiate ()
{
if(document.getElementsByClassName)
{
var links = document.getElementsByClassName("external-link");
for (var i = 0; i < links.length; i++) {
links[i].onclick = confirmLeave;
}
} else {
var links = document.getElementsByTagName("external-link");
for (var i = 0; i < links.length; i++) {
links[i].onclick = confirmLeave;
}
}
}
window.onload = initiate;
The external-link
is the class I'm using for the links that are to leave my webpage.
Upvotes: 0
Views: 233
Reputation: 15765
The problem here is that document.getElementsByTagName()
takes an element as it's input, e.g. div
, span
or a
. external-link
is not an element, so it'll never return anything.
For IE8, you can use document.querySelectorAll(".external-link")
. It takes a CSS selector as it's input.
If you need to support older browsers too, you could try using https://gist.github.com/2397759 which is a polyfill to make getElementsByClassName
work on browsers that don't support it natively.
Upvotes: 0
Reputation: 1
consider including jQuery library if that's a viable option for you. then you may write something like this:
$('.external-link').click(function() { confirmLeave() });
Upvotes: 0