0

I have 4 divs on an HTML page which represent links to social media sites.

Rather thank have 4 different blocks of Javascript is there a way to loop this code so I don't have to write it out for every option pair in the two arrays?

var socialDiv=["facebook","twitter","google","linkedin"];
var URL=["http://www.facebook.com","http://www.twitter.com","http://www.google.com","http://www.linkedin.com"];
  
document.getElementById(socialDiv[0]).onclick=function(){
window.open(URL[0],'_blank');
}

I have tried using For and While loops which half worked. All the divs listed in the first array became clickable, but all opened blank windows.

This is what I had previously tried:

var socialDiv=["facebook","twitter","google","linkedin"];
var URL=["http://www.facebook.com","http://www.twitter.com","http://www.google.com","http://www.linkedin.com"];
var i=0;

while(i<socialDiv.length){
    document.getElementById(socialDiv[i]).onclick=function(){
    window.open(URL[i],'_blank');
    }
  i++;
}
Ashley
  • 1
  • 1
  • What about var URL as an object with name:url key value pairs? – Oakley Nov 16 '14 at 15:52
  • 1
    You have only one `i` variable in your scope that is shared between all event handlers, and has the value `4`. See the linked duplicate on how to solve this. – Bergi Nov 16 '14 at 15:54

0 Answers0