TheGreatBenigma
TheGreatBenigma

Reputation: 51

onClick in a for loop is not firing

What I have below is code from a recent tutorial of Computer Arts magazine. What I have tried to do is implement an onClick function within the loop so that each div is clickable and will load the corresponding webpage.

I have an array, currently with only one set of values but you can get the idea of multiple values that are similar:

var itemsHTML = '',
        items = [
        {
          itemType:'ani',
          itemName:'Show Reel 10-11',
          path:'thumb_showreel.jpg',
          urlPath:'showreel.html'
        }];

And the loop that takes the info from the array (Please take note of the onClick - this is my input, everything else is from the tutorial:

    for(var i = 0; i < items.length; i++) {
      var type = items[i]['itemType'];
      var name = items[i]['itemName'];
      var path = items[i]['path'];
      var urlPath = items[i]['urlPath'];
      itemsHTML += "    <div class=\"element " + type + "\"  style=\"background-image:url('portfolio/" + type + "/" + path + "')\" onClick=\"document.location='http://www.thepapertorium.co.uk/'" + urlPath + "\">";
      itemsHTML += "      <div class=\"label\">";
      itemsHTML += "        <h1>" + name + "<\/h1>";
      itemsHTML += "      <\/div>";
      itemsHTML += "    <\/div>";
    }

This same onClick was taken from my header's banner. It works correctly there, so I figured I could paste it into here, and, naturally, adhere it to the syntax that the for loop requires, but I have had no luck. Please help with this simple dilemma!

Upvotes: 1

Views: 318

Answers (3)

mplungjan
mplungjan

Reputation: 177786

Quotes issue - I simplified them for you by reversing the " and '

I also added ; cursor:pointer and changed document.location to window.location since that is more correct. Actually bfavaretto is indeed correct in saying you do not need a javascript to change the page - a link will even give you the pointer for free

DEMO

itemsHTML += '<div class="element ' + type + '" style="background-image:url(\'portfolio/' + type + '/' + path + '\')" onClick="window.location=\'http://www.thepapertorium.co.uk/' + urlPath + '\'">';

Next time try jsfiddle.net and firebug

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71908

I think your problem is document.location instead of window.location. But I wouldn't use javascript for that, you could use an anchor tag instead:

itemsHTML += "    <a class=\"element " + type + "\"  style=\"display: block; background-image:url('portfolio/" + type + "/" + path + "')\" href=\"http://www.thepapertorium.co.uk/" + urlPath + "\">";

Upvotes: 1

maialithar
maialithar

Reputation: 3123

Your problem may be in single ' - it should go to the end of URL:

onClick=\"document.location='http://www.thepapertorium.co.uk/" + urlPath + "'\"

Upvotes: 4

Related Questions