i have a problem a little bit like this one :
jQuery onclick doesn't work on a button with data-toggle and data-target
But i can't apply the solution from @epascarello to my problem
I'm using bootstrap and I want to add a collapse and an onclick action on the same < a>
<a class="control" data-toggle="collapse" data-target="#demo"onclick="play('audioPlayer', this)">
If I delete the data-toggle part, the onclick works, and if i delete the onclick part, the data-toggle works,
Could anyone help me ?
Thank you :)
i have a problem a little bit like this one :
jQuery onclick doesn't work on a button with data-toggle and data-target
But i can't apply the solution from @epascarello to my problem
I'm using bootstrap and I want to add a collapse and an onclick action on the same < a>
<a class="control" data-toggle="collapse" data-target="#demo"onclick="play('audioPlayer', this)">
If I delete the data-toggle part, the onclick works, and if i delete the onclick part, the data-toggle works,
Could anyone help me ?
Thank you :)
Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Jan 27, 2016 at 10:11 GuillaumeGuillaume 531 gold badge1 silver badge6 bronze badges 3- @epascarello will you be my savior – Guillaume Commented Jan 27, 2016 at 10:12
- why cant you use delegated event as mentioned in epascarello answer – Amar Singh Commented Jan 27, 2016 at 10:15
- Yes but i don't understand how to apply this to my code :( – Guillaume Commented Jan 27, 2016 at 10:18
2 Answers
Reset to default 3First give a id to your a tag
<a id="YourID" class="control" data-toggle="collapse"
data-target="#demo"onclick="play('audioPlayer', this)">
and than your JS
$(document).on("click", "#YourID", function() {
alert("Test");
});
Try this first
This is called delegated event handlers .You can refer to: http://api.jquery./on/
EXPLANATION
With delegated event handlers, you attach your event handlers
to the parent
element that exists at the time we run the code (it's document
in this case). When the child elements are clicked (no event handlers), the event is bubbled up by browser and is handled by its parent (with event handlers attached)
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers
Similarly in vanilla JS:
<ul class="nav nav-tabs">
<li><a href="#name_ref" data-toggle="tab" id="name_id">My Tab Label</a>
</li>
</ul>
later...
<div class="tab-pane fade" id="name_ref">
<div class="panel-heading">Content</div>
</div>
later...
<script>
document
.getElementById("name_id")
.addEventListener("click", function(event) { console.log("event");});
</script>