Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - opening all links on a page

Tags:

jquery

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?

like image 213
Jason Avatar asked Dec 14 '22 06:12

Jason


1 Answers

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)

like image 69
Owen Avatar answered Dec 18 '22 00:12

Owen