0

I'm somewhat new to Javascript but know enough that I'm aware I shouldn't be writing my Javascript inline with my HTML but instead loading it from an external file. I've been trying to put it in an external file, but because of the way my code works I think it would be better to arrange it in functions that can be called at various points. What is the best practice for this?

At a guess, I'd say I should be wrapping all the JS in a singular file and then calling each code fragment with a function... but I'm not entirely sure how to do that and I'm not knowledgeable enough to know how to pose the question to look around online.

Here's a sample:

<html>
<script type="text/javascript"> <!--Create the arrays-->
    var locationLat = new Array();
    var locationLong = new Array();
    var postURL = new Array();
    var postExcerpt = new Array();
    var postTitle = new Array();
    var featImg = new Array();

    var i = 0;
</script>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript"> <!--Load data from Wordpress into the arrays so we can use them on a map later-->
    locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
    locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
    postURL[i] = "<?php echo get_permalink( $id );?>";
    postExcerpt[i] = "<?php echo  get_the_excerpt();?>";
    postTitle[i] = "<?php echo get_the_title($ID);?>";
    featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"

    i++;
</script>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<script type="text/javascript">
function initialize() { <!--**I tried putting this function into an external JS file and calling it onLoad with body but it didn't do anythin**g-->
    google.maps.visualRefresh = true;
    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(37.09024,-95.712891),
        disableDefaultUI: true,
    };

    var posts = locationLat.length;
    var j = 0;
    var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
    var place = new Array();

        while (posts != j)
        {
            var image = '<?php echo get_template_directory_uri(); ?>/location_marker.png';
            var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);

            place[j] = new google.maps.Marker({
                position: myLatLng,
                map: map,
                icon: image,
                url: postURL[j],
                excerpt: postExcerpt[j],
                title: postTitle[j],
                cover: featImg[j]
            });   

            google.maps.event.addListener(place[j], 'click', function() {
            map.panTo(this.getPosition());
            map.setZoom(8);

            $('#spantext').html(this.title);
            $('#poste').html(this.excerpt);
            $('.fillme').html('<img src="' + this.cover + '">');
            $('.readmore').html('<p><a href="' + this.url + '">Read more ></a>');
            $('.sidebar').show().stop().animate({
                'width' : '400px',
                'opacity' : '1'
            }, 500);
            });
            j++;
        }
} 

google.maps.event.addDomListener(window, 'load', initialize);
</script>

<body>

If I'm completely off track, some guidance would be good. Everything works in this format but I really don't think it's correct. I'm aware this is a relatively dumb question, but in lieu of finding a really good answer anywhere I thought it was worth asking.

Herp
  • 263
  • 1
  • 3
  • 13
  • It depends where you put the `script` tags. For the most part, `script` tags are loaded in place as the page loads. If the page is processed first as PHP, you may need to factor that in to how you have written it. One option is to have JS scripts initialized in a common function called `init()` which is set as the default action of the `document.onload` event. – abiessu Aug 04 '13 at 02:52
  • I'm guessing the correct way to do this would be to load in my JS file immediately after the CSS file and use something like [this](http://stackoverflow.com/a/9530992/744961) to call the initialize function, for example – Herp Aug 04 '13 at 02:54
  • Yes, but more than that, you must depend on your PHP code being complete prior to any Javascript code being executed. Also, yes, put all functions in (an) external file(s). Then they are easier to manage properly. – abiessu Aug 04 '13 at 03:01
  • Just a tip: instead of var SomeArray = new Array(); you should use var SomeArray = []; and same for objects where var SomeObject = {}; instead of new Object(); You can use google to find out why. – frenchie Aug 04 '13 at 03:04
  • Oh nice - thanks for that. Had a look and found why not to so have updated my code. Cheers! – Herp Aug 04 '13 at 03:09
  • @Herp Don't update the question itself. Add the edits to the question & leave the earlier part as such... so that someone might find it useful someday. – loxxy Aug 04 '13 at 03:12

1 Answers1

0

I would suggest to put the different piceces of js into different files & add them with php.

But for that, first tailor the js to be independent chunks i.e one piece of js should not be accessing variables from another.

So it would look something like :

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript" src="myScript.js"> 
</script>

Contents of myScript.js

<!--Load data from Wordpress into the arrays so we can use them on a map later-->
    locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
    locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
    postURL[i] = "<?php echo get_permalink( $id );?>";
    postExcerpt[i] = "<?php echo  get_the_excerpt();?>";
    postTitle[i] = "<?php echo get_the_title($ID);?>";
    featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"

    i++;
loxxy
  • 12,990
  • 2
  • 25
  • 56