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.

6
  • 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. Commented Aug 4, 2013 at 2: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 to call the initialize function, for example Commented Aug 4, 2013 at 2: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. Commented Aug 4, 2013 at 3: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. Commented Aug 4, 2013 at 3:04
  • Oh nice - thanks for that. Had a look and found why not to so have updated my code. Cheers! Commented Aug 4, 2013 at 3:09

1 Answer 1

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++;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.