I dynamically add an <a> (link) tag to the DOM with:
var link = document.createElement('a');
link.href = 'http://www.google.com/';
link.onclick = function () { window.open(this.href); return false; };
link.appendChild(document.createTextNode('Google'));
//someDomNode.appendChild(link);
I want the link to open in a new window (I know it's bad, but it's required). I also tried to use the "target" attribute, but I also have the wrong behavior with this solution too.
My code works well in IE and Firefox, but the return false don't work in Safari, Chrome and Opera. By don't work I mean the link is followed after the new window is opened.
I think I might be because of the Google Maps V3 environment...
Edit: To see the behavior on the actual page:
Any help is welcome!
Edit2: The problem is in function "MakeInfoWindowContent" which is in "gmaps3.js". I don't use DOM to create the elements (I use string) because this HTML string must be passed to Google Maps (for the info window - the balloon). In fact the same link is created at 2 different places. One on the left, created with DOM function (as shown in this question) which works in all browsers and one in the balloon, created with an HTML string, this one don't work well in Safari, Chrome and Opera (the link is followed after the new window open even with the return false).
Edit 3: Still no clue why this is happening... If anyone have an idea, let me know!
Would preventing default action for the event work maybe? Not sure if gmaps handles links in it's info window in some other way, if not, it should work.
Update: first example didn't work. The event wasn't passed when using "inline" onclick to assign event. This one is tested and found to be working.
function bindEvent(target, event, handler) {
if (typeof target.addEventListener != 'undefined') {
target.addEventListener(event, handler, false);
} else if (typeof target.attachEvent != 'undefined') {
target.attachEvent('on' + event, handler);
}
}
var link = document.createElement('a');
link.href = 'http://www.google.com/';
link.appendChild(document.createTextNode('Google'));
bindEvent(link, 'click', function (e) {
if (typeof e.preventDefault != 'undefined') {
// Common/W3C events
e.preventDefault();
}
// (Old) IE specific events
e.returnValue = false;
var target = e.target || e.srcElement;
window.open(target.href);
return false;
});
document.getElementsByTagName('body')[0].appendChild(link);
Set the href
to 'javascript:void(0);'
and instead of referencing this.href
inside your onclick handler, hard-code the URL there instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With