Anchor Tag with Prevented Default Behavior Not Executing Correctly

35 Views Asked by At

I'm encountering a peculiar issue within Haml views where a clickable image is configured within an anchor tag. The desired behavior is to execute an Ajax call when the image "Button" is clicked. However, despite various attempts, including using javascript:void(0) and href='', to prevent the anchor tag's default behavior, the Ajax call doesn't execute as expected (which means the #generic-button.button event was not called). It's worth noting that using href='' results in an unwanted page reload, and using href='#' also does not help.

When we first land on the form, the click on the button does not invoke the event (I've verified through console logs), but if I reload the page the button click works and whatever's inside the event function happens as it should.

Expected Behaviour:

Upon clicking the clickable image when first landing on the page, the Ajax call should execute, I'm using Ajax call as an example here, It could be any thing inside the event function.

Note: In my case I've verified the Ajax call is working as expected but the clickable image's behaviour is the problem here. Another thing to note here is that reloading the url makes the Ajax call/clickable image work.

here's what I have setup:

%a#generic-button.button{'data-generic-id' => generic-id, :href => 'javascript:void(0);'}
  = image_tag('https://www.example.com/test/generic-button.svg', id: 'Generic Image')

and the Ajax call:

$(document).on('click', '#generic-button.button', function(event) {
  event.preventDefault();
  var genericId = $(this).data('generic-id');

  $.ajax({
    url: '/generic-action',
    method: 'POST',
    headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') },
    data: { generic_id: genericId },
    success: function(response) {
      if (response.success) {
        // Handle success logic here
      }
    },
    error: function() {
      // Handle error logic here
    }
  });
});
0

There are 0 best solutions below