As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:
This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
You can use GetChildAtPoint() to determine if the mouse is over a child control.
private void panel1_MouseLeave(object sender, EventArgs e)
{
if (panel1.GetChildAtPoint(panel1.PointToClient(MousePosition)) == null)
{
panel1.BackColor = Color.Gray;
}
}
If the control isn't actually a child control, you can still use MousePosition and PointToScreen to determine if the mouse is still within the bounds of the control.
private void panel1_MouseLeave(object sender, EventArgs e)
{
Rectangle screenBounds = new Rectangle(this.PointToScreen(panel1.Location), panel1.Size);
if (!screenBounds.Contains(MousePosition))
{
panel1.BackColor = Color.Gray;
}
}
Best Answer
Your description leads me to believe that you want both your child and your parent controls to respond to a click on the child control.
If I understand your question correctly, I'd suggest subscribing to your child controls' click events and, in those event handlers, calling some common method that manipulates the state of the parent UserControl in the manner that you desire (e.g., changing the background color).