Reputation:
I am trying to use Jquery to search a table of images for any that match the defined parameters within the src, and if found to then open the href in a new window. The href comes before the img src in the website code, which I believe I've compensated for in my Jquery.
Unfortunately I'm unsure why the Jquery is not working - could anybody take a look at it and give me a nudge in the right direction? I suspect the problem is in opening the specified href, but for the life of me I can't spot the problem. Thanks in advance.
$('img[src$=random.gif]').each(function() {
$img = $(this);
$link = $url.closest('a');
var href = $link.attr('href');
var win = window.open.attr('href', '_blank');
win.focus();
});
setTimeout(function () { window.location.href = window.location.href }, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<a href="/link">
<img src="/random.gif">
</a>
</td>
Upvotes: 0
Views: 56
Reputation: 206121
If $img
is the $(this)
image than instead of $url.closest('a');
you should point to $img
$img = $(this);
$link = $img.closest('a');
Edited example: https://jsfiddle.net/4ua4p5pf/
$('img[src$="random.gif"]').each(function() {
var $img = $(this);
var href = $img.closest('a').attr('href');
setTimeout(function () {
var win = window.open( href, "Image description", "status,resizable,scrollbars");
// var win = window.open( href, "image"); // open in new tab
win.focus();
}, 500);
});
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
window.open with target "_blank" in Chrome
Upvotes: 1