0

This has been bugging me as I'm not really sure what is going on but it feels like a beginner problem. Basically I have a button that displays a chat box if clicked, and another button that just acts as a link to a further section of the page.

  • If I click the chat button first, my Jquery code is called and it displays correctly
  • If I click the anchor link button first, I am indeed going to the right section; but clicking the chat button afterwards does not call the Jquery code anymore (click event not registered)

HTML code:

<a href="#what-you-get" class="btn btn-white btn-border radius-lger min-width"><strong>Learn More</strong></a>
<a href="#" data-role="toggle-chatbot" data-display="1" class="btn btn-white radius-lger min-width"><strong>Join Our Waitlist</strong></a>

JS code:

$(function () {

  // Shows or hides the chatbot
  $('[data-role="toggle-chatbot"]').on('click', function(e) {
    e.preventDefault();
    if($(this).attr('data-display') == '1') {
      $('.container-chat').removeClass('hide');
    }
    else {
      $('.container-chat').addClass('hide');
    }
  });

});

Any suggestion? Thanks in advance!

EDIT: Solved thanks to this. The problem was due to Turbolinks in Ruby on Rails 5 and the following code fixed things (the change to .toggle-chatbot was to optimise things based on Rajesh's comment):

$(document).on('turbolinks:load', function () {
  // Shows or hides the chatbot
  $('.toggle-chatbot').on('click', function(e) {
    e.preventDefault();
    if($(this).attr('data-display') == '1') {
      $('.container-chat').removeClass('hide');
    }
    else {
      $('.container-chat').addClass('hide');
    }
  });

});
Community
  • 1
  • 1
Davor
  • 1,227
  • 4
  • 15
  • 31
  • 1
    Just a pointer, `$('[data-role="toggle-chatbot"]')` is an expensive query. Have a unique class instead. Also about your issue, it would be a lot easier of you can create a Fiddle or a stack snippet, where we can debug it – Rajesh Nov 12 '16 at 13:43
  • Seems to work for me: https://jsfiddle.net/59worfp0/ –  Nov 12 '16 at 13:45
  • Thanks to both - looks like the issue comes from somewhere else. Weirdly, if I add target="_blank" to the first link, the code will work fine in both the old and new tab. Any idea of a direction where I could dig more? I'm not even sure what other code would be relevant to show you. – Davor Nov 12 '16 at 14:08
  • Actually the issue seems to come from something else entirely - in Ruby on Rails (http://stackoverflow.com/questions/17600093/rails-javascript-not-loading-after-clicking-through-link-to-helper). I'll play with that as I'm pretty sure this is the culprit. – Davor Nov 12 '16 at 14:11

0 Answers0