I’m trying to hijack a button element so I can open it’s link in a new window. I’ve added a new attribute the elements which need to open in a new window called data-ext-link="true". In some cases the button element has a onclick which contains the location.href that I need to send the user to. How can I grab that location.href using jquery so I can supply it to the window.open in my function?
The function below works great for anchor elements, but it’s within my is('button') if statement where it gets hairy and doesn’t work because attr() returns an object and not a string. The object It returns is the following:
My Button Code:
<button data-ext-link="true" onclick="location.href='http://website/url_i_want'" class="btn2">Open it up</button>
$.attr(‘onclick’) Response:
function onclick(event) {
location.href = "http://website.com/url_i_want";
}
My Function:
function extLinks() {
var extLinks = $('a[data-ext-link="true"], button[data-ext-link="true"]');
$.each(extLinks, function(){
if($(this).is('button')){
var link = $(this).attr('onclick'); // Here it needs to be a string.
link = link.match(/location.href='(.*)'/); //Won't work because it's an object.
link = link[1];
} else {
var link = $(this).attr('href');
}
$(this).unbind('click.extLink').bind('click.extLink',function(e){
e.preventDefault();
window.open(link);
});
});
}
UPDATE:
I found the following related question which suggest using $.live which being deprecated I’d use $.delagate() instead, but this doesn’t fully address the issue where I need to tell this button to open in a new window using it’s location.href value inside the onclick as the target.
SOLUTION:
function extLinks() {
var extLinks = $('a[data-ext-link="true"], button[data-ext-link="true"]');
$.each(extLinks, function(){
if($(this).is('button')){
var link = this.onclick.toString().match(/location\.href\s*=\s*['"]([^'"]*)['"]/)[1];
} else {
var link = $(this).attr('href');
}
$(this).unbind('click.extLink').bind('click.extLink',function(e){
e.preventDefault();
window.open(link);
});
});
}
Try to convert the function to a string:
Note – I don’t know if this will work in all browsers. Works for me in Firefox and IE7 though.
Also, you may need to revise your regular expression – it won’t work for the example you posted. Try this:
I’ve confirmed that this solution does work for me. Here’s an example page: http://nylen.tv/test-onclick.html