btsyir
btsyir

Reputation: 11

Invoking jquery from code behind

I need to make a HyperLink blink (customer requirement unfortunately) so I've decided to use this.

Could someone point me in the right direction on how to invoke this from the code behind (C#)?

So far I've tried:

private string script1 = "<script type=\"text/javascript\" charset=\"utf-8\" src=\"javascripts/jquery.blink.min.js\"></script>";
private string script2 = "$(\".selector\").blink();";
ScriptManager.RegisterClientScriptBlock(e.Item.FindControl("hlink"), e.Item.FindControl("hlink").GetType(),
                    "BlinkingScript", script1, false);
ScriptManager.RegisterStartupScript(e.Item.FindControl("hlink"),
                                                    e.Item.FindControl("hlink").GetType(),
                                                    "BlinkingScript", script2, false);

..to no avail

Upvotes: 1

Views: 468

Answers (1)

GalacticCowboy
GalacticCowboy

Reputation: 11769

Trying to mess around with RegisterClientScriptBlock and RegisterStartupScript is painful, and is completely unnecessary except in some extremely off-radar edge cases. Not only is it extremely difficult to maintain, it's also difficult to understand. And in this case the simple, direct approach will work much better for you.

In the <head> block of your page, add the following:

<!-- Assuming that you've already got jQuery registered... -->
<script language="javascript" type="text/javascript" src="Scripts/jquery.blink.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        // Couple of notes here:
        // ".blinky" means that it will match anything with a CSS class of "blinky".  This can be anything, not just hyperlinks.
        // Also, I'm adding an optional object parameter to the blink() method that allows me to specify parameters that alter its behavior.
        // In this case, if I just called blink() it would only blink 3 times, but I'm overriding that to blink 5 times.
        $(".blinky").blink({blinks: 5});
    });
</script>

Then, in the body of your page, add the CssClass="blinky" on the hyperlinks that you want to blink.

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#" Text="Not Blinky Link" /><br />
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="#" Text="Not Blinky Link" /><br />
<asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="#" Text="Blinky Link" CssClass="blinky" /><br />
<asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="#" Text="Not Blinky Link" /><br />
<asp:HyperLink ID="HyperLink5" runat="server" NavigateUrl="#" Text="Blinky Link" CssClass="blinky" /><br />
<asp:HyperLink ID="HyperLink6" runat="server" NavigateUrl="#" Text="Blinky Link" CssClass="blinky" /><br />

You can also use an asp:Repeater, code-behind, etc. to construct your Hyperlink items, just as long as you set the CssClass on the ones you want to blink.

Upvotes: 2

Related Questions