Using Javascript To Dynamically Create Links That Trigger Popup Windows
Solution 1:
The proper way to achieve what you need would be the event delegation. That is, you assign the event handler to a parent element (like <body>
), and check the event target inside.
For example, you may have the following HTML:
<divid="container"><ahref="http://www.domain.com/page.php">Page 1</a><ahref="http://www.domain.com/page2.php">Page 2</a></div><buttonid="addBtn">Add a new link</button>
Note that every link has a proper href
attribute that will be used for popup windows. It will also serve as a fallback for the case when Javascript is disabled.
And the (simplified — I don't check for element type, nor the existence of href property) script would be:
var container = document.getElementById('container');
container.addEventListener('click', function (e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; // For IE
}
var target = e.target;
var popupWindow = window.open(target.href,'popUpWindow',
'height=400,
width=500,
left=10,
top=10,
resizable=yes,
scrollbars=yes,
toolbar=yes,
menubar=no,
location=no,
directories=no,
status=yes'
);
});
// The following code creates links dynamically upon clicking the button
document.getElementById('addBtn').addEventListener('click', function (e) {
var index = container.getElementsByTagName('a').length + 1;
var newLink = '<a href="http://www.domain.com/page' + index +'.php">Page ' + index +'</a>';
container.innerHTML += newLink;
});
See the example here: http://jsfiddle.net/C53cd/3/. Works for me in FF16 and Chrome. Note that you might need to implement a simple polyfill for event binding to work in IE (MSIE and addEventListener Problem in Javascript?). Alternatively, you can use jQuery for the same purpose.
UPD: Added default action prevention for IE.
UPD 2: Added the code to create the new links dynamically.
Post a Comment for "Using Javascript To Dynamically Create Links That Trigger Popup Windows"