Rails Javascript - Converting jQuery to Javascript not working using Rails 7
P粉436688931
P粉436688931 2024-01-16 22:01:23
0
1
552

Rails 7 with Turbo/Hotwire. I'm reusing code copied from an old project from 2018. This code/jQuery is for the information popup:

$(document).ready(function() {
      $('#info').hover(function() {
        $('#popup').show();
        }, function() {
        $('#popup').hide();
        });
      });

After rewriting the javascript (correct?), this is what I'm currently testing - without success:

$(document).addEventListener("DOMContentLoaded", function() {
      $('#info_1').onmouseover(function() {
        $('#popup_1').show();
        }, function() {
        $('#popup_1').hide();
        });
      });

I have #info_1 / id=info_1 In a div, popup #popup_1 / id=popup_1 Directly below another div.

I've tested placing the javascript in the app/javascript/custom/menu.js file, as well as using it in the tag on the view page.

How should I handle this.

Thanks

P粉436688931
P粉436688931

reply all(1)
P粉846294303

$() means you are still using jquery, you have not converted it to pure JavaScript, but you have converted it to broken jquery. Every line using the $().someChained function needs to be replaced. For example:

$(Documentation).addEventListener

should be

Documentation.addEventListener

This is the gist of what you want, there is a note to note about DOMContentLoaded, if it loads before the listener is bound it will never fire.

document.addEventListener('DOMContentLoaded', function() {
  var info = document.getElementById('info');
  var popup = document.getElementById('popup');

  info.addEventListener('mouseenter', function() {
    popup.style.display = 'block';
  });

  info.addEventListener('mouseleave', function() {
    popup.style.display = 'none';
  });
});

Side note, if you need to replace a non-trivial project jquery with plain js, and you are not familiar with the language at all, then this is going to be a very, very difficult task.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template