The ASP.Net jQuery dialog will only appear the first time it is hovered over and will not reappear upon subsequent h

Within my User Control, there is an UpdatePanel containing a Repeater with Linkbuttons nested inside:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RelatedEntityControl.ascx.cs" Inherits="MyApp.Controls.Layout.RelatedURLControl" %>
<asp:UpdatePanel ID="RelatedObjectsPanel" runat="server">
<ContentTemplate>
 <script type="text/javascript">
        function openPopup(url, h, w, t, link) {
            {
                if (url != null && h != null && w != null && t != null && link != null) {
                    var btn = document.getElementById(link);
                    var top_distance = btn.getBoundingClientRect().top;
                    var left_distance = btn.getBoundingClientRect().left;
                    var myDialogX = left_distance - w/2;
                    var myDialogY = top_distance;
                    $('#PreviewWindow').html('<iframe style="border: 0px; " width="100%" height ="100%" src="' + url + '"> </iframe>');
                    $("#PreviewWindow").dialog({
                        title: t,
                        modal: false,
                        autoOpen: true,
                        height: h,
                        width: w,
                        closeOnEscape: true,
                        position: [myDialogX, myDialogY],
                        dialogClass: 'dialog_fixed,ui-widget-header',
                        open: function (event, ui) {
                            $(this).css('overflow', 'hidden'); //this line does the actual hiding of the vertical scrollbar
                        }
                    });
                }
            };
        }
    </script>
    <script type="text/javascript">
        $(function () {
            var btn = $('.previewLink');
            btn.hoverIntent(function (e) {
                e.target.click();
            }, function () { });
        });
    </script>

        <asp:Panel ID="URLPanel" runat="server" Visible="false">
        <asp:CollapsiblePanelExtender ID="URLsCollapsiblePanel" runat="server" CollapseControlID="URLsLabel" ExpandControlID="URLsLabel" TargetControlID="URLsPanel" TextLabelID="URLsLabel"
            CollapsedText="[ + ]  Related URLs" ExpandedText="[ - ]  Related URLs" />
        <asp:Label ID="URLsLabel" runat="server" CssClass="collapsiblePanelHeader" Text="" Width="90%"></asp:Label>
        <asp:Panel ID="URLsPanel" runat="server" CssClass="collapsiblePanelContent" style="height: auto;">

            <asp:Repeater ID="URLsLocalRepeater" runat="server" OnItemDataBound="LocalRepeater_ItemDataBound" ItemType="SSPS.Models.Relationships.RelatedURL">
                <HeaderTemplate>
                    <ul>
                </HeaderTemplate>
                <ItemTemplate>
                    <li>
                        <asp:HyperLink ID="HyperLink1" Text='<%# Item.Title %>' NavigateUrl='<%# Item.ActualLink %>' runat="server" Target="_blank" ToolTip='<%# Item.ToolTip %>'></asp:HyperLink>&nbsp;&nbsp;<asp:LinkButton ID="PreviewButton" runat="server" CausesValidation="false" Text="preview" OnClick="PreviewButton_Click" Font-Size="X-Small"  CssClass="previewLink"></asp:LinkButton>
                        <div id="PreviewWindow"></div>
                    </li>
                </ItemTemplate>
                <FooterTemplate>
                    </ul>
                </FooterTemplate>
            </asp:Repeater>
        </asp:Panel>
    </asp:Panel> 
</ContentTemplate>

The hoverIntent function in Javascript activates when hovering over the LinkButtons. Once activated, it triggers a click event on the LinkButton which leads to server-side processing within PreviewButton_Click() method:

protected void PreviewButton_Click(object sender, EventArgs e)
{
    //figure out the loc, url and so forth
    string loc = ResolveUrl("~/PreviewWindow.aspx");
    loc += "?url=" + url.ActualLink;
    ScriptManager.RegisterStartupScript(this, this.GetType(), "dlg", "openPopup('" + loc + "', " + url.HintHeight + ", " + url.HintWidth + ", '" + url.Title + "', '" + previewButton.ClientID + "')", true);
    return;
}

After successfully opening the jQuery dialog through hovering or clicking on a LinkButton, encountering issues arise upon closing the dialog. Subsequent attempts to hover over another LinkButton fail to trigger the PreviewButton_Click() method as expected. This problem seems to be related to a postback issue that interferes with the Javascript functionality.

In attempting to resolve this issue, removal of the hoverintent function revealed that manual clicking on the LinkButton consistently opens the dialog without failure. It suggests that the root cause may lie within the handling of the postback event impacting the script execution flow.

Further exploration into this scenario has led to observations suggesting that any postback actions within the UserControl disrupt the stability of the jQuery dialog appearance. Despite troubleshooting efforts, including examining the JavaScript code for errors using Chrome's inspect window, the underlying issue remains unresolved.

Your insights and suggestions would be greatly appreciated.

Update: Following recommendations from @mjw and @WebDev, additional peculiar behavior patterns have surfaced. Notably, performing any action within the UserControl resulting in a postback directly affects the functioning of the jQuery dialog mechanism. The continuous loss of hoverIntent activation during subsequent interactions emphasizes the complexity of resolving the postback-related impediments on the JavaScript interaction dynamics.

Answer №1

There is a problem with the ASP.Net page lifecycle.

  1. The first hover works because you register the hover event handler using this JS code

However, after a postback, ASP.NET re-renders everything inside the updatepanel, making previously registered handlers invalid. This means that elements selected before have no association with newly rendered elements.

It's similar to having an <a> element with a click handler, removing it, and then creating a new one. The HTML may look the same, but the click handler won't work because it's not connected to the new element.

  1. $(function(){ .... }); acts as a shorthand for document ready and only fires once when the document is ready. After a postback, this function isn't triggered, leading to newly created elements without any JS handlers.

To fix this issue, move the script block below the panels (but still inside the updatepanel) and remove the document ready shorthand like so:

<script>
............
var btn = $('.previewLink');
btn.hoverIntent(function (e) {
   e.target.click();
}, function () { });
</script>

[UPDATE]

You can try this solution:

protected void Page_PreRender(object sender, EventArgs e)
    {
        var script = @"
        var btn = $('.previewLink');
                btn.hoverIntent(function (e) {
                    e.target.click();
                }, function () { });
        ";

        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "someKey",
            script, true);
    }

I hope this helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Tabulator: The top and bottom calculations do not shift position when a column is toggled. Seeking a solution to toggle a column and refresh the table without losing the current

My main objective is to toggle the visibility of toggles while maintaining consistent formatting. However, I currently face an issue where using a filter achieves this but results in losing the current scroll position of the tabulator, which is not accepta ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...

Executing the removal by _id command in mongodb does not function as intended

Initially, I thought implementing a delete function for my mongodb in the MEAN stack would be straightforward. However, I've encountered issues and haven't found a solution on Google or Stack Overflow. In my application, I am working with Users ...

Working with conditional statements in ReactJS and Javascript

As I navigate the circle object using arrow keys, I am facing a challenge in limiting its movement within the height and width of the svg area. Despite my efforts to use conditional statements, the ball tends to get trapped at the edges and fails to contin ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

Guidelines on receiving a user's color input and showcasing it with JavaScript

/* Take a color input from the user and apply it to the variable called "message". */ <script type="text/javascript"> var textcol, message = "Great choice of color!"; textcol=window.prompt("Please enter a color:&quo ...

Is it possible to gradually open or close a div element?

Looking for a way to add an effect to the code below that opens/closes a div on mouseover above an image. Any examples or suggestions? I'm not exactly a javascript expert. HTML: <div> <div class="under"><img src="http://oi60.tinypic.c ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Struggling with altering inherited scope within a directive link function (specifically in the implementation of a Konami code

Note: Check out the working plunker for this directive with a solution: http://embed.plnkr.co/UhFCVa/ I am attempting to develop a directive that will activate a debug mode by detecting keystrokes. I can see the "debug mode toggle" message, indicating tha ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

Unable to show the same error message in multiple locations using identical code

I am facing an issue where error messages are not displaying for an empty input field, while they work perfectly fine for a textarea. The if statement for the inputName seems to be working, but the else statement is not being triggered. What could be causi ...

How can I access the binary data source of an image using ASP.NET?

Is there a way to preview an image before uploading it in an ASP.NET webform? I have tried using the code below, but now I am stuck on how to upload the image to the server after clicking the Save button. When checking my codebehind, I found that the <i ...

Generating a unique array in C# without any duplicate elements

Currently, I'm facing an issue with my code where it's creating duplicates. I require assistance with this for my school project. It would be greatly appreciated if you could also provide some explanation along with the solution. Please ignore th ...

Leveraging mongoose populate in a Node.js environment with TypeScript

I am struggling to solve this issue. I am currently working on a node express mongoose server with code written in TypeScript and encountering the following error: Property 'populate' does not exist on type 'Document | Aggregate | Model | ...

Troubleshooting Guide: Resolving npm Error Code EINVALIDTAGNAME During Package Publishing

node -v 20.18.0 npm -v 10.9.0 Hey there! I've encountered an issue - whenever I attempt to use any npx init command, I encounter an error. For instance, npx init prisma The same error occurs when I try to initialize husky. PS C:\Users\User ...

"Troubleshooting: How to Fix Issues with document.getElementById on Dynamic Div

Struggling to incorporate div elements and generate graphs with Google charts? The issue arises in the draw function, where attempts to access a div element using document.getElementById() result in null values and an error message stating "container not ...

Ways to Implement an Origin's First-Party Cookies While Using it as a Third-Party

Imagine I am the owner of a website called "treat1creator.com". I want my clients, who are also website owners, to send HTTP requests to my server that contain cookies I have generated. Here is how it works: User "Sally" visits my site at treat1creator.co ...

Leverage the event manager to automatically reload the page upon detecting a specific string

I currently have this code in place to update a codebox on the page with data retrieved from dyntask.php. <script type="text/javascript"> if(typeof(EventSource)!=="undefined") { var eSource = new EventSource("dyntasks.php ...