0

I have two scripts, one external and one internal in my html document. I wanted to combine them in to one external javascript file. Unfortunately when I put the internal one inside the external one the internal scripts functions do no seem to work. I can't see why it wont.

The combined script below and separated into what was internal and what was external.

//INTERNAL SCRIPT
    var x = 0, y = 0,
        vx = 0, vy = 0,
        ax = 0, ay = 0;

    var points;


    var sphere = document.getElementById("sphere");
    var counting = false;
    var counter = 0;
    var numberOne;

    if (window.DeviceMotionEvent != undefined) {
        window.ondevicemotion = function(e) {

            ax = event.accelerationIncludingGravity.x * 5;
            ay = event.accelerationIncludingGravity.y * 5;

            document.getElementById("counterSpan").innerHTML = Math.round(counter*10)/10;
            //document.getElementById("accelerationX").innerHTML = Math.round(e.accelerationIncludingGravity.x * 10)/10;
            //document.getElementById("accelerationY").innerHTML = Math.round(e.accelerationIncludingGravity.y * 10)/10;
            //document.getElementById("accelerationZ").innerHTML = Math.round(e.accelerationIncludingGravity.z * 10)/10;

            var moveX = Math.round(e.accelerationIncludingGravity.x * 10)/10;
            //var moveY = Math.round(e.accelerationIncludingGravity.y * 10)/10;
            //var moveZ = Math.round(e.accelerationIncludingGravity.z * 10)/10;

            if(moveX > 5 || moveX < -5) {
                counting = true;
                //alert(counting);
                if(counter < 100){counter+=0.01;}
                }




            if ( e.rotationRate ) {
                //document.getElementById("rotationAlpha").innerHTML = Math.round(e.rotationRate.alpha * 10)/10;
                //document.getElementById("rotationBeta").innerHTML = Math.round(e.rotationRate.beta * 10)/10;
                //document.getElementById("rotationGamma").innerHTML = Math.round(e.rotationRate.gamma * 10)/10;
            }       
        }


    $( "#btnEnergize" ).click(function() {

      numberOne = $("#numberOne").val();
            alert(numberOne);
          localStorage.setItem('points',numberOne);

            if (numberOne <= counter){
            counter-=numberOne;
            }
            else {
            alert("Not enough Energize points");    
            }


    });

        setInterval( function() {
            var landscapeOrientation = window.innerWidth/window.innerHeight > 1;
            if ( landscapeOrientation) {
                vx = vx + ay;
                vy = vy + ax;
            } else {
                vy = vy - ay;
                vx = vx + ax;
            }
            vx = vx * 0.98;
            vy = vy * 0.98;
            y = parseInt(y + vy / 50);
            x = parseInt(x + vx / 50);

            boundingBoxCheck();

            //sphere.style.top = y + "px";
            //sphere.style.left = x + "px";

        }, 25);
    } 


    function boundingBoxCheck(){
        if (x<0) { x = 0; vx = -vx; }
        if (y<0) { y = 0; vy = -vy; }
        if (x>document.documentElement.clientWidth-20) { x = document.documentElement.clientWidth-20; vx = -vx; }
        if (y>document.documentElement.clientHeight-20) { y = document.documentElement.clientHeight-20; vy = -vy; }

    }

    function minmax(value, min, max) 
    {
        if(parseInt(value) < 0 || isNaN(value)) 
            return 0; 
        else if(parseInt(value) > 100) 
            return 100; 
        else return value;

    }



    //EXTERNAL SCRIPT

    jQuery(function($){



      var $overlay = $('.overlay'),
          resize = true,
          map;
        var service;
        var marker = [];
        var pos;
        var infowindow;
        var placeLoc
        var markerValue = [];
        var markers


    function initialize() {
      /*var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

    }*/
    var mapOptions = {
        zoom: 15
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

      // Try HTML5 geolocation
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

                var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

            var request = {
          location:pos,
          center:pos,
          radius:1000,

      };

      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request,callback);
          pos = new google.maps.LatLng(position.coords.latitude,
                                           position.coords.longitude);


            infowindow = new google.maps.InfoWindow({
            map: map,
            position: pos,
            content: 'You Are Here'
          });
            $('#findMe').data('pos',pos);

          map.setCenter(pos);
        }, function() {
          handleNoGeolocation(true);
        });
      } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
      }



      function callback(results, status) {
          markers = [];
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          markers.push(createMarker(results[i]));
        }
      }
      $('#findMe').data('markers',markers);
    }
    }



    function createMarker(place) {


        placeLoc = place.geometry.location;

      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 8,
            fillColor:'00a14b',
            fillOpacity:0.3,
            fillStroke: '00a14b',       
            strokeWeight:4,
            strokeOpacity: 0.7
        },




      });


      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
      });
      return marker;
    }

    function handleNoGeolocation(errorFlag) {
      if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
      } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
      }

      var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
      };

      var infowindow = new google.maps.InfoWindow(options);
      map.setCenter(options.position);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    $('#show').click(function(){

        $overlay.show();

      if ( resize ){
        google.maps.event.trigger(map, 'resize');
        resize = false;
      }

    });

    $('.overlay-bg').click(function(){

        $overlay.hide();

    });




    $( "#findMe" ).click(function() {



      var pos     = $(this).data('pos'),
          markers = $(this).data('markers'),
          closest;


      if(!pos || !markers){
        return;
      }

      $.each(markers,function(){
        var distance=google.maps.geometry.spherical
                      .computeDistanceBetween(this.getPosition(),pos);
        if(!closest || closest.distance > distance){
          closest={marker:this,
                   distance:distance}
        }
      });
      if(closest){
        //closest.marker will be the nearest marker, do something with it
        //here we simply trigger a click, which will open the InfoWindow 
        google.maps.event.trigger(closest.marker,'click')


         var Loc2 =  closest.marker.getPosition();


         for (var i=0; i<markers.length; i++) {
             var Loc1 = markers[i].getPosition()



            if (Loc1.equals(Loc2)){
                console.log("its the same");
                console.log("marker array Location 1 " + Loc1 + " marker " + i);
                console.log("closest Location 2 " +Loc2);

                markerValue[i] = numberOne;

                console.log( "marker " + i + " now equals " + markerValue[i]);

            }

         }
      }

    });


    });
5
  • Can you give us some more information about what doesn't work? Errors given, line numbers, that sort of thing. That's a lot of text to digest without a hint about where to look. Commented Feb 11, 2014 at 21:40
  • move your internal code inside of the jQuery(function($){ .. }). My guess is that its a DOM loading issue Commented Feb 11, 2014 at 21:40
  • always make sure any code interacting with the DOM is a window.onload or jQuery ready event handler, like your external script was. Commented Feb 11, 2014 at 21:40
  • Are you including the script before certain elements exist. If you put that in a script tag before the element with the id sphere exists, then it clearly won't work, because document.getElementById("sphere"); will be null. Commented Feb 11, 2014 at 21:40
  • Typically, people put internal <script>s after external <script>s. If your includes were before your internal script, then you changed the order of execution. Maybe pasting the internal after the external will fix it. Commented Feb 11, 2014 at 21:41

1 Answer 1

1

If you look at your external code, it's in a shorthand jQuery ready event handler. Since your internal code interacts with the DOM, you should make sure it's also running in that same event handler context.

Likely your internal code was inside a onload function, at the bottom of the page, or maybe within its own ready event handler and you forgot to take that into account.

Sign up to request clarification or add additional context in comments.

2 Comments

I think that has fixed it, if I move all the external variables to the top they should be global to the whole script right? so if I wanted to add a function which interacts with variables between the scripts it will be able to do that?
@DanKristianWilliams I typically keep all my function declarations and any needed global element reference variables defined outside of onload / ready. Any init code just typically gets and caches those DOM references, and then assigns event handlers. I try to keep the init code clean and small, and delegated to function calls if possible, while everything else is usually just event handlers ready to be assigned using addEventListener. essentially it's just bootstrap code.

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.