Search code examples
javascripthtmlprintinghrefincrement

Adding javascript incremented filenames into html a tag


I have a list of pictures that need to be displayed. The list of pictures is very large (500+) and I did not want to load each by individually naming them in the html code for the href attribute of the a tag. Hence, I used javascript to generate filenames incremented by 1, which produces the correct filepath. Here is the javascript:

function bigpicture()
    {
        var filepath = "\"images/print/latest/" ;
        var ext = ".png\"";
        var total = filepath + num + ext;
        document.write(total)
        num = num + 1;
    }

When I call bigpicture() I get the correct filepath and name, and all multiple calls it increments as well. My problem is getting this string to display after the href attribute of my a tag, as seen here:

HTML

<div class = "big">
        <ul>    
            <li>
                <a href=<script>bigpicture()</script> rel="lightbox" title=""><img class="floated_img" img src="images/print/latest/small/1.png" /></a>
            </li>

        </ul>
</div>

I assumed (incorrectly) that I could call the function like this, but it does not work. Could anyone tell me how to execute the script in a way that the sting appears after href? Thank you.


Solution

  • The way your doing it won't work because the function call is not bound to any event in your html code like an onload or onsubmit and therefore won't execute.

    I would use jQuery to append to your ul in the big div. Your call to bigpicture() could look like this:

    <script>
    
      function bigpicture()
      {
        var filepath = "./images/print/latest/" ;
        var ext = ".png\"";
        for(var i = 0; i < numOfPictures; i++){
            $('#big ul').append('<li>' + filepath + i + ext + '</li>');
          }
    
      }
    
      $(function(){     //this is jQuery shorthand for document ready
          bigpicture(); //anything in this anonymous function will execute
        })              //after HTML document has been loaded
    
    </script>
    

    The document ready info comes from here