I have a button which needs to run a javascript function when clicked.
The problem is that this button lives within another element which has it’s own click function which seems to be preventing that of the button from running.
Here’s the code:
<a id="login">Login
<span>
<span style="display:block; padding:0 0 5px 0;">
content here...
</span>
<input type="button" id="forgotten" value="test" />
</span>
</a>
And here’s the javascript:
$("#login").click( function() {
$("#login > span").slideDown();
});
$('body').click( function() {
if ($("#login > span:visible")) {
$("#login > span").slideUp();
}
});
$('#login, #login > span').click( function(event){
event.stopPropagation();
});
$("#forgotten").live("click", function() {
// ... Run function here...
});
I have a feeling it might be because of the stopPropagation part of the code.
Any ideas?
The
livefunction attaches the handler to thedocumentelement and waits for the event to propagate. You are correct in thinking that preventing the event from propagating is preventing the handler being called. You can work around this using thedelegatemethod (similar to live, but with specified parent elements rather thandocument):Or in jQuery 1.7+ the
onmethod can be used: