Harnish
Harnish

Reputation: 101

Calling a function in cesium.js when a event is trigerred

I have a div created as below

<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar"><input type="search" id="search" placeholder="Search by layout name" onkeydown="search()"/></div>

So when enter button is pressed in search box, it should call the function "Search".

<script id="cesium_sandcastle_script">
function startup(Cesium) {
'use strict';
 var west = 68.0;
 var south = 7.0;
 var east = 89.0;
 var north = 35.0;
 var rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);

 Cesium.Camera.DEFAULT_VIEW_FACTOR = 0.5;
 Cesium.Camera.DEFAULT_VIEW_RECTANGLE = rectangle;
 var viewer = new Cesium.Viewer('cesiumContainer', {
   timeline: false,
   animation : false,
   vrButton : true,
   selectionIndicator : false
 });


   function search() {
      alert("success");
   }
 }

When i run this it is raising an error "search is not a function". Where am i wrong?

Upvotes: 1

Views: 681

Answers (1)

emackey
emackey

Reputation: 12418

The problem is that Cesium Sandcastle wraps your code in a startup function, as you can see in the first line of JavaScript in your question above, and this shields local declarations from the global scope. So there's no window.search function to bind to. But binding global functions like this isn't best practice these days.

Give this a try instead: remove the onkeydown="search()" attribute from your HTML code above, and instead subscribe to the event in JavaScript like so:

function search() {
    console.log('testing search...');
}

document.getElementById('search').addEventListener('keypress', search, false);

Upvotes: 1

Related Questions