Last night I gave a jQuery presentation at TVBUG and I was asked whether you could call the jQuery API directly from within Silverlight. My initial response was yes, but I had promise the person that I would create a demo and blog about it.
Calling Javascript from within Silverlight control involves the following steps;
- Add a using System.Windows.Browser namespace to the code behind of the Silverlight control.
- Creating a ScriptObject by calling HtmlPage.Window.CreateInstance.
- Calling the Invoke method off the ScriptObject from step 2.
Let’s look at some code.
The listing below contains a code snippet that is run when a Silverlight button is clicked.
23 private void btn_Click(object sender, RoutedEventArgs e)
24 {
25 ScriptObject js = HtmlPage.Window.CreateInstance("$", new string[] { "#hello" });
26 js.Invoke("css", "background-color", "#00FF00");
27 js.Invoke("css","border","5px solid #FF0000");
28 }
Notice the parameters to the HtmlPage.Window.CreateInstance static member shown on line 25 contains the call to jQuery function $() and the selector #hello. This call returns a ScriptObject and can subsequently be used to invoke functions off the jQuery object. In this example, I am first setting the background of the DOM element with id of hello to red and then setting it’s border.
I have a working demo of this just navigate to this site.