Reputation: 2388
so I have a very simple code
$("#toggle_google").trigger("click");
$("#toggle_google").click();
$("[id^='toggle_']").on("click", function() {
console.log("clicked: " + $(this).attr("id").replace("toggle_", "").toString());
return false;
});
$("#toggle_google").on("click", function() {
console.log("clicked toggle_google");
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<a href="www.google.com" id="toggle_google">Google</a>
<br>
<a href="javascript:void(0)" id="toggle_bing">Bing</a>
</p>
I don't get anything on my console when the page loads. If I click on the links, I get messages on my console.
I've come up with my code after reading various discussions in stackoverflow and also reading jquery.com
Any ideas why it isn't working?
Here's a jsfiddle link
Upvotes: 0
Views: 109
Reputation: 5962
You have defined your click event after calling , so just revers it. and it will work fine.
$("[id^='toggle_']").on("click", function() {
console.log("clicked: " + $(this).attr("id").replace("toggle_", "").toString());
});
$("#toggle_google").on("click", function() {
console.log("clicked google");
});
$("#toggle_google").trigger("click");
$("#toggle_google").click();
Upvotes: 1