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');
}
});
});