I am programming in VB.NET. I am trying to make an onClick event for a div tag. How can I make this in the code behind?
One possible solution would be to create a Webusercontrol with a Panel(will be rendered as DIV) and an invisible Button(Display:none). Onclick of the div you could click the button per javascript which would cause an automatic Postback. In Codebehind you would catch that ButtonClick-Event and Raise a custom event(DivClicked). So you can reuse that control everywhere. Something like this:
ClickableDiv.ascx
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ClickableDiv.ascx.vb" Inherits="WebApplication1.ClickableDiv" %>
<asp:Panel id="TheDiv" runat="server" onMouseOver="this.style.cursor='pointer'" onclick="this.nextSibling.click()" /><asp:Button ID="DivButton" runat="server" />
ClickableDiv.ascx Codebehind
Partial Public Class ClickableDiv
Inherits System.Web.UI.UserControl
Public Event DivClicked(ByVal src As ClickableDiv)
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Me.DivButton.Style.Add("display", "none")
End Sub
Public ReadOnly Property Div() As Panel
Get
Return Me.TheDiv
End Get
End Property
Protected Sub DivButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DivButton.Click
RaiseEvent DivClicked(Me)
End Sub
End Class
And for example in any page(drag&drop it to the designer):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim imgTest As New Image
imgTest.ImageUrl = "http://skins.gmodules.com/ig/images/logos/approved/white.png"
Me.ClickableDiv1.Div.Controls.Add(imgTest)
End Sub
Private Sub ClickableDiv1_DivClicked(ByVal src As ClickableDiv) Handles ClickableDiv1.DivClicked
Dim div As ClickableDiv = src
End Sub
Btw, you could also use the __doPostback-function on the DIV's onclick event to raise a Postback.
1- create hidden asp:button
2- on div click document.getElementById('<%=HiddenButton.ClientID%>').click();
this will fire button_click event on server
** remember to set UseSubmitBehaviour=false
for the hidden button to make click event works