Question

I need to adapt javascript from html template to my gwt code. The original code in head is:

<script src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/slimbox.js"></script>
<script type="text/javascript" src="assets/js/slider.js"></script>

<script type="text/javascript">
$(document).ready(function(){
  $("#slider").easySlider({
    auto: true,
    continuous: true,
    controlsShow:    false,
  });
});
</script>

and in body:

<div id="slider">
  <ul>
    <li><a href="#"><img src="myapp/img/01.jpg" alt="" /></a></li>
    <li><a href="#"><img src="myapp/img/02.jpg" alt="" /></a></li>
    <li><a href="#"><img src="myapp/img/03.jpg" alt="" /></a></li>
    <li><a href="#"><img src="myapp/img/04.jpg" alt="" /></a></li>
    <li><a href="#"><img src="myapp/img/05.jpg" alt="" /></a></li>
  </ul>
</div>

I have linked external javascripts in MyApp.jsp

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
  <script type="text/javascript" language="javascript" src="myapp/myapp.nocache.js"></script>
  <script type="text/javascript" language="javascript" src="myapp/js/jquery.js"></script>
  <script type="text/javascript" language="javascript" src="myapp/js/slimbox.js"></script>
  <script type="text/javascript" language="javascript" src="myapp/js/slider.js"></script>
</head>

Then I have MainPage.java, which creation is handled by History

public MainPage() {
    initWidget(uiBinder.createAndBindUi(this));
    RootLayoutPanel.get().clear();
    RootLayoutPanel.get().add(this);
    onLoadSlider();
}

public static native void onLoadSlider() /*-{
    $("#slider").easySlider({
    auto: true,
    continuous: true,
    controlsShow: false,
});
}-*/;

calling the onLoadSlider function results to exception: onLoadSlider()([]): $ is not defined

then I tried to use window.top.document.getElementById("slider") instead of $("#slider") and exception is now onLoadSlider()([]): undefined is not a function

Was it helpful?

Solution

As you can read up in the official dev guide for JSNI, you have to prepend $wnd here:

$wnd.$("#slider").easySlider({
    auto: true,
    continuous: true,
    controlsShow: false,
});

When accessing the browser's window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page's window and document.

OTHER TIPS

Try

$wnd.parent.document.getElementById("slider")

instead of

window.top.document.getElementById("slider")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top