14

I have a basic url redirect on a DIV's onclick.

<div onclick="location.href = 'page.aspx';">

I have a need to do some work server side, rather than just a redirect, when this Div is clicked.

How do I call one of my code behind functions from the DIV onclick? The DIV is the parent control inside a usercontrol. I suppose I can "fix" it by using a literal control and writing a query string into the onclick, but I would use that as a last resort as I don't want to use a query string.

Are there any other ways of catching a DIV click in code behind that I may have missed?

2
  • 1
    My guess would be a JQuery function on the div onclick event that is linked to an Ajax enabled webservice on the server end. Commented Jul 26, 2013 at 7:36
  • Is __doPostBack what you are looking for? Commented Jul 26, 2013 at 7:41

1 Answer 1

24

You can have a button whose display can be 'none'. Handle click of Div on client side and then from there fire the Click of that button and handle the thinks Server Side on the Click Event of the button.

<asp:Button runat="server" id="btnHidden" style="display:none" onclick="btnHidden_OnClick" />
<div onclick="javascript:DivClicked(); return true;"></div>

<script>

function DivClicked()
{
    var btnHidden = $('#<%= btnHidden.ClientID %>');
    if(btnHidden != null)
    {
        btnHidden.click();
    }
}

</script>
Sign up to request clarification or add additional context in comments.

4 Comments

That's pretty much what I am asking in my question. :-)
always use ClientID as the control could be wrapped with any other control (a GridView, ContentPlaceHolder, List, etc)
Thank you, but the var btnHidden = $('#<%= btnHidden.ClientID %>'); didnt worked for me, so had to replace for var btnHidden = document.getElementById('btnHidden');, not sure if getElementById is the best option, hope it helps someone
Thanks for the useful answer, but just curious, in nclick="javascript:DivClicked(); return true;" why did you bother having it return true?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.