Reputation: 13
I have this problem when using event listeners and jQuery. For some reason the events keep firing twice.
Here is the JavaScript:
jQuery(document).ready(function(){
function tioOverload(e){
var tioButton = e.explicitOriginalTarget;
var path = tioButton.name;
jQuery.ajax({
url : ajax_object.ajaxurl,
type : 'post',
data : {
path : path,
action : "bpnsc_tio_enable"
},
success : function(data) {
console.log('Success enabled ' + data);
},
error : function(data){
console.log(data);
console.log("failed");
}
});
}
var tioEn = document.getElementsByClassName("tio-enable");
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioOverload);
}
});
The PHP:
function bpnsc_tio_enable() {
$path = $_POST['path'];
echo $path;
die();
}
add_action( 'wp_ajax_bpnsc_tio_enable', 'bpnsc_tio_enable');
and the HTML for the image I'm triggering the action from:
<img class="tio-enable" name="Test Feature" src="/image.png">
If I remove the jQuery and simply load the JavaScript on document.ready the event handler only fires once per mouseclick, with jQuery it is firing twice. I can't remove the jQuery because I need to use AJAX.
Upvotes: 1
Views: 749
Reputation: 48
$(".tio-enable").off().on('click', function(){
// your code here
});
Use this code instead of looping through all the elements and attaching the events.
Hope this helps.
Upvotes: 3