Joe Peteny Joe Peteny - 2 months ago 6
Javascript Question

why file js is called two times

I have this button:

<button type="button" id="topic_schedulati" class="btn btn-info">Mostra Topics Schedulati</button>


This is my jquery code to handle the click:

(function() {
$(window).on('action:ajaxify.end', function(event, data) {

if (new RegExp(/^category\/[0-9]+/).test(data.url)) {
$(document).ready(function(){
$('body').on('click', '#topic_schedulati', function() {
console.log("hi");
});
});
}

});
}());


Why when I click on the button I show the print "hi" two times and not one? Anyone can help me?

Answer

Most likely this action "action:ajaxify.end" is being called multiple times. As you're attaching the event to the body there is no need for your other conditions as the event will be responsive to any added element that matches the id "topic_schedulati" keep in mind that you should only have 1 element with that id or you'll have erratic behavior depending on the browser.

$(function() {
    $('body').on('click', '#topic_schedulati', function() {
            console.log("hi");
    });
});