My problem is with correctly toggle-ing the state of some buttons. I use jquery click events. And I’m sorry for the long post, but I don’t know where the problem is and don’t want to accidentally miss it. I searched for similar questions but none seemed to fix my problem.
I start rendering a div containing some tasks I want to do for today. And I want to be able to toggle them as being done or not.
{
$('#currentDiv').hide();
rewriteDivFromScratch();
$('#eachday').show();
}
Where the rewriteDivFromScratch adds button divs to HTML:
<div id="eachday"> .. </div>
<div id="button-0" class="button"> <button class="btn btn-mini"> .. </button> </div>
..
<div id="button-7" class="button"> <button class="btn btn-mini"> .. </button> </div>
function rewriteDivFromScratch() {
el = $("#eachday");
// get the HTML divs from Handlebars templating compilation
// they're OK, I checked with inspector
// This renderes nicely, no problem here.
el.html(html);
}
I add a click event for buttons to toggle in the same file with those above:
$('.btn-mini').click( function(e) {
e.preventDefault();
var el = $(e.currentTarget); // the <button />
el.toggleClass('btn-inverse');
}
And I get no toggleing effect..
Now, I suppose this happens because there is not .btn-mini class by the time the $(..).click executes. This is why I added a setInterval like so:
var intervalId; // it's global in my js file
function rewriteDivFromScratch() {
...
// This renderes nicely, no problem here.
el.html(html);
intervalId = setInterval(check); // this fires only once, so seems OK
}
var check = function() {
$('.btn-mini').click( function(e) {
e.preventDefault();
var el = $(e.currentTarget); // the <button />
if (el.length)
clearInterval(intervalId);
else
return;
// It executes this toggle more than **15** times per
// click on button.. Now, why is that?
el.toggleClass('btn-inverse');
}
};
As I’ve said in the above last comment, my problem is that that part gets executed multiple times, not a fixed number of times per refresh, in order to find a pattern or something.
The above js code is in a single ‘app.js’ which I simply include in my index.html like any other script.
just use jquery’s ‘live’ for a ‘delegated event’, which will also work whenever new buttons are inserted into the document:
see http://api.jquery.com/live/ for further explanations of how ‘live’ works.