I have a very basic rails 6 app created with a single controller and index view, which looks like:
$ cat app/views/welcome/index.html.erb
<%= javascript_pack_tag 'hide_link' %>
<%= link_to "back here", root_url %>
<br \>
<%= link_to "Should Disappear", root_path, id: 'be_gone', remote: true %>
The javascript being included in hide_link looks like:
$ cat app/javascript/packs/hide_link.js
window.addEventListener('load', () => {
//document.addEventListener('DOMContentLoaded', () => {
//window.onload = () => {
let link = document.getElementById('be_gone');
if (link) {
link.onclick = () => link.style.display = "none";
}
console.log("In hide_link"); // just here to let me know it is running
} , false);
After starting the server the page accurately displays the 2 links and I have the Developer Tools open on the Console page so as to see my message "In hide_link". It also shows the following information:
hide_link.js:10
This appears on the far right of the Console. Clicking the link "Should Disappear", does in fact disappear when clicked, but, when I click the "back here" link the page is refreshed and the following change is made in the Console window:
hide_link.js:10
#replaced by
VM58 hide_link-8e7e6…20e4f0e3eed3.js:107
Now the VM58 and the random characters after hide_link- change each time I retry the process, but the issue is that from this point on, although I can once again see the "Should Disappear" link, once clicked on it will no longer disappear until I refresh the entire page!!
So my question is, has anyone else come across this issue and hence a resolution?
Also, is it an issue with rails 6, webpacker or javascript or a combination of one or all?
Please let me know if any additional information can be provided to help in a solution?
Turns out the solution can be found on the following page:
https://guides.rubyonrails.org/working_with_javascript_in_rails.html#page-change-events
And the gist is to change the following:
window.addEventListener('load', () => {
# to
window.addEventListener('turbolinks:load', () => {
All my javascripts are working even after being redirected back to the same page using a link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.