tags:

views:

912

answers:

1

I'm trying to learn jQuery, to make up for my anemic javascript skills.

As a test project, I have a page full of links, and I want to have a button on the page open all the links in new tabs. The links all have target="_blank" attributes.

I'm using this

  $('button').click(function() {
    $('a').click();
  );}

I've tested the selector syntax by modifying the css of the links, so I'm sure that is ok. What do I need to change in order to get the link to open?

+9  A: 

you can't manipulate tabs via javascript (you can ask a link to open in a new window, you just can't tell it to open in a tab). what you might want to try if you want to try is something like this:

$('button').click(function() {
  $('a').each(function() {
     window.open($(this).attr('href') );
  });
});

essentially, when <button> is clicked, for each <a> element, pass the href value to window.open. or basically, piles of open windows assuming you have no pop up blocker :)

your current code basically says, when you press <button>, activate the onclick() handler of all <a> elements.

edit: in response to comments, compare this code that mimics the OP's functionality:

$('a').click(function() {
// assign an event to a.onclick
  window.open($(this).attr('href') );
});

$('button').click(function() {
// when we press <button>, trigger a.onclick
  $('a').click();
});

because we declared an onclick() functionality first, we now have the same behaviour as my original code. (piles of open windows)

Owen
While I understand your code and also that one cant open links in tabs, what is wrong with the code that OP has provided?Thanks.
shahkalpesh
the OP's code will toggle the onclick event handler of each <a> element. however, assuming that's the only code, onclick is undefined, and thus nothing happens
Owen
Actually, the .each() syntax worked for what I needed. In the context I'm using it, it causes each link to open in it's own tab, not window. Since this is for my own use, I'm not concerned about it being bulletproof for other users/browsers.
Jason