Reputation: 197
I'm trying to open a link as soon as you open the page (by forcing a click) with jQuery, but it doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('a.bla').click(function(){
window.open(this.href);
return false;
});
});
</script>
</head>
<body>
<a href="url-to-open.php" target="_blank" class='bla'><img src="pic.png" alt="" style="border:none;" /></a>
</body>
</html>
I have no clue what's wrong. I hope someone of you knows how to fix this.
Upvotes: 0
Views: 76
Reputation: 16685
This example should cause the new window to open automatically via a link click event. (Haven't tested this, may need to pass the href
value into the handler as a data
argument.
$(document).ready( function() {
var $link = $( 'a.bla' ),
href= $link.attr( 'href' );
$link.unbind( 'click' ).bind( 'click', function ( e ) {
window.open( href );
e.preventDefault();
e.stopPropagation();
} );
$link.click();
});
Upvotes: 0
Reputation: 55750
Try
window.open($(this).attr('href'));
instead of
window.open(this.href);
If you want to open on page load.. Just move this line outside of the click event and it should be fine.
Upvotes: 1
Reputation: 92983
Your code will not open a link as soon as you load the page; it creates an event handler that triggers a function as soon as you load the page. That event handler is only triggered when you click on the link.
Now, what you would normally do is:
$(document).ready(function(){
$('a.bla').trigger('click');
});
Except that won't open the link, because for security reasons, you can't programmatically trigger a mouse click -- you can only programmatically trigger the event handler assigned to that mouse click.
Try this:
$(document).ready(function(){
window.open($('a.bla').attr('href'),'name-of-new-window');
});
Which will work, unless of course the user has a popup blocker stopping it.
Upvotes: 2
Reputation: 148160
Use .
for class not #
$(document).ready(function(){
$('a.bla').click(function(){
window.open(this.href);
return false;
});
});
As indicated that using #
is by mistake.
$(document).ready(function(){
window.open($('a .bla').href);
return false;
});
Upvotes: 1
Reputation: 5283
$('a.bla').click(function(){
should be
<script>
$(document).ready(function(){
$('a.bla').click(function(){
window.open($(this).attr("href"));
return false;
});
});
Upvotes: 1